1. 程式人生 > 其它 >2022-4-13 面試高頻題

2022-4-13 面試高頻題

341. 扁平化巢狀列表迭代器

給你一個巢狀的整數列表 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,繼續重複判斷。