博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
22. 平面列表
阅读量:4560 次
发布时间:2019-06-08

本文共 1422 字,大约阅读时间需要 4 分钟。

给定一个列表,该列表中的每个要素要么是个列表,要么是整数。将其变成一个只包含整数的简单列表。

易错点:nestedList.get(i).getInteger(),取集合中的元素时忘记get(i),,就取不到了

扩展:怎么用非递归来解答

思路:比较简单,直接递归调用即可。

  1. /** 
  2.  * // This is the interface that allows for creating nested lists. 
  3.  * // You should not implement it, or speculate about its implementation 
  4.  * public interface NestedInteger { 
  5.  * 
  6.  *     // @return true if this NestedInteger holds a single integer, 
  7.  *     // rather than a nested list. 
  8.  *     public boolean isInteger(); 
  9.  * 
  10.  *     // @return the single integer that this NestedInteger holds, 
  11.  *     // if it holds a single integer 
  12.  *     // Return null if this NestedInteger holds a nested list 
  13.  *     public Integer getInteger(); 
  14.  * 
  15.  *     // @return the nested list that this NestedInteger holds, 
  16.  *     // if it holds a nested list 
  17.  *     // Return null if this NestedInteger holds a single integer 
  18.  *     public List<NestedInteger> getList(); 
  19.  * } 
  20.  */  
  21. public class Solution {  
  22.   
  23.     // @param nestedList a list of NestedInteger  
  24.     // @return a list of integer  
  25.     public List<Integer> flatten(List<NestedInteger> nestedList) {  
  26.         // Write your code here  
  27.         List<Integer> list=new ArrayList<>();  
  28.         doFlatten(nestedList,list);  
  29.         return list;  
  30.     }  
  31.      public void doFlatten(List<NestedInteger> nestedList,List<Integer> list){  
  32.          if(nestedList != null){  
  33.              for(int i=0;i<nestedList.size();i++){  
  34.                  if(nestedList.get(i).isInteger()){  
  35.                      list.add(nestedList.get(i).getInteger());  
  36.                  }else{  
  37.                      doFlatten(nestedList.get(i).getList(),list);  
  38.                  }  
  39.              }  
  40.          }  
  41.      }  
  42. }  
 

转载于:https://www.cnblogs.com/Pjson/p/8289426.html

你可能感兴趣的文章
(转)使用 python Matplotlib 库绘图
查看>>
进程/线程切换原则
查看>>
正则表达式语法
查看>>
20165301 2017-2018-2 《Java程序设计》第四周学习总结
查看>>
Vue的简单入门
查看>>
urllib 中的异常处理
查看>>
通过SQL Server的扩展事件来跟踪SQL语句在运行时,时间都消耗到哪儿了?
查看>>
WIFI密码破解全攻略
查看>>
gulp
查看>>
pgsql查询优化之模糊查询
查看>>
不变模式
查看>>
matlab去云雾
查看>>
500lines项目简介
查看>>
Asp.net core logging 日志
查看>>
BOM浏览器对象模型
查看>>
Jq 遍历each()方法
查看>>
Android源码分析:Telephony部分–phone进程
查看>>
20181227 新的目标
查看>>
HDFS写流程
查看>>
使用命令wsimport构建WebService客户端[转]
查看>>