2022-4-13 面试高频题
给你一个嵌套的整数列表 nestedList
。每个元素要么是一个整数,要么是一个列表;该列表的元素也可能是整数或者是其他列表。请你实现一个迭代器将其扁平化,使之能够遍历这个列表中的所有整数。
实现扁平迭代器类 NestedIterator
:
NestedIterator(List<NestedInteger> nestedList)
用嵌套列表nestedList
初始化迭代器。int next()
返回嵌套列表的下一个整数。boolean hasNext()
如果仍然存在待迭代的整数,返回true
;否则,返回false
。
你的代码将会用下述伪代码检测:
initialize iterator with nestedList res = [] while iterator.hasNext() append iterator.next() to the end of res return res
如果 res
与预期的扁平化列表匹配,那么你的代码将会被判为正确。
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, rather than a nested list. 7 * public boolean isInteger(); 8 * 9 * // @return the single integer that this NestedInteger holds, if it holds a single integer 10 * // Return null if this NestedInteger holds a nested list 11 * public Integer getInteger(); 12 * 13 * // @return the nested list that this NestedInteger holds, if it holds a nested list 14 * // Return empty list if this NestedInteger holds a single integer 15 * public List<NestedInteger> getList(); 16 * } 17 */ 18 public class NestedIterator implements Iterator<Integer> { 19 private List<NestedInteger> nestedList; 20 private int index=0; 21 private int size; 22 private NestedIterator iterator=null; 23 public NestedIterator(List<NestedInteger> nestedList) { 24 this.nestedList=nestedList; 25 this.size=nestedList.size(); 26 } 27 28 @Override 29 public Integer next() { 30 NestedInteger cur=nestedList.get(index); 31 if (cur.isInteger()) { 32 index++; 33 return cur.getInteger(); 34 }else { 35 return iterator.next(); 36 } 37 } 38 39 @Override 40 public boolean hasNext() { 41 while (index<size){ 42 NestedInteger cur=nestedList.get(index); 43 if (cur.isInteger()) { 44 return true; 45 }else { 46 if (iterator==null) { 47 iterator=new NestedIterator(cur.getList()); 48 } 49 if (iterator.hasNext()){ 50 return true; 51 }else { 52 index++; 53 iterator=null; 54 } 55 56 } 57 } 58 return false; 59 } 60 } 61 62 /** 63 * Your NestedIterator object will be instantiated and called as such: 64 * NestedIterator i = new NestedIterator(nestedList); 65 * while (i.hasNext()) v[f()] = i.next(); 66 */
思路:对于next函数,判断当前是否为数字,是数字直接返回,否则返回当前迭代器的下一个。因为执行next之前会判断hasnext,所以迭代器不会为空。
hasnext方法,首先index不能超过size,其次判断当前是否为数字,是返回true。否则为列表,如果迭代器为空则递归生成当前列表的迭代器,如果hasnext为true,则返回true,否则index+1,继续重复判断。