zoukankan      html  css  js  c++  java
  • 22. 平面列表

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

    易错点: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. }  
     
  • 相关阅读:
    三位数
    顺序表应用4:元素位置互换之逆置算法
    顺序表应用5:有序顺序表归并
    顺序表应用6:有序顺序表查询
    数据结构实验之图论八:欧拉回路
    串结构练习——字符串连接 Description
    图的基本存储的基本方式三
    数据结构实验之图论四:迷宫探索
    数据结构实验之图论二:图的深度遍历
    图的基本存储的基本方式二
  • 原文地址:https://www.cnblogs.com/Pjson/p/8289426.html
Copyright © 2011-2022 走看看