首頁>技術>

簡介: 演算法面試真題詳解:巢狀列表的加權和II

描述給一個巢狀的整數列表, 返回列表中所有整數由它們的深度加權後的總和. 每一個元素可能是一個整數或一個列表(其元素也可能是整數或列表)。注意,在之前的題目巢狀列表的加權和中,從根結點到葉子結點,深度權重是遞增的。在巢狀列表的加權和II中,深度權重的定義是自下而上的,也就是說,最底層葉子結點的深度權重是1 ,根結點的深度權重最大。

線上評測地址:領釦題庫官網

樣例 1:輸入: nestedList = [[1,1],2,[1,1]]輸出: 8解釋:四個深度為1的1,一個深度為2的2
樣例 2:輸入: nestedList = [1,[4,[6]]]輸出: 17解釋:一個深度為3的1, 一個深度為2的4,和一個深度為3的6。1*3 + 4*2 + 6*1 = 17
主要思路:

bfs遍歷列表每一層,如果是數字,則加到當前這一層的和當中,反之,是列表,則進入佇列,每一層遍歷完,才進入下一層,最後將每一層的數值加到結果當中即可。

public class Solution {    /**     * @param nestedList: a list of NestedInteger     * @return: the sum     */    public int depthSumInverse(List<NestedInteger> nestedList) {         // corner case         if(nestedList == null || nestedList.size() == 0) {             return 0;         }          // initialize         int preSum = 0;         int result = 0;         // put each item of list into the queue         Queue<NestedInteger> queue = new LinkedList<>(nestedList);         while(!queue.isEmpty()){             //depends on different depth, queue size is changeable             int size = queue.size();             int levelSum = 0;             for(int i = 0; i < size; i++){                 NestedInteger n = queue.poll();                 if(n.isInteger()){                     levelSum += n.getInteger();                 }                 else{                     // depends on different depth, queue size is changeable                     queue.addAll(n.getList());                 }             }             preSum += levelSum;             result += preSum;         }         return result;    }}

5
最新評論
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • 小白學視覺31個Python專案掌握影象處理,PDF開放下載