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. }  
     
  • 相关阅读:
    一次脑残的记录: Linux 中实时任务调度与优先级
    这 7 个 Linux 命令,你是怎么来使用的?
    物联网设备OTA软件升级之:完全升级和增量升级
    物联网设备OTA软件升级之:升级包下载过程之旅
    Linux应用程序设计:用一种讨巧方式,来获取线程栈的使用信息
    Linux系统中编译、链接的基石-ELF文件:扒开它的层层外衣,从字节码的粒度来探索
    应用程序设计:在动态库中如何调用外部函数?
    Typescript学习笔记
    gRPC 重试策略
    Gogs+Jenkins+Docker 自动化部署.NetCore
  • 原文地址:https://www.cnblogs.com/Pjson/p/8289426.html
Copyright © 2011-2022 走看看