Problem
Given a nested list of integers, return the sum of all integers in the list weighted by their depth.
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
Example 1:
Input: [[1,1],2,[1,1]]
Output: 10
Explanation: Four 1"s at depth 2, one 2 at depth 1.
Example 2:
Input: [1,[4,[6]]]
Output: 27
Explanation: One 1 at depth 1, one 4 at depth 2, and one 6 at depth 3; 1 + 42 + 63 = 27.
/** * // @return true if this NestedInteger holds a single integer, rather than a nested list. * public boolean isInteger(); * // @return the single integer that this NestedInteger holds, if it holds a single integer * public Integer getInteger(); * // @return the nested list that this NestedInteger holds, if it holds a nested list * public ListgetList(); */ class Solution { public int depthSum(List nestedList) { return helper(nestedList, 1); } private int helper(List list, int level) { int res = 0; for (NestedInteger item: list) { if (item.isInteger()) res += (level*item.getInteger()); else { res += helper(item.getList(), level+1); } } return res; } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://www.ezyhdfw.cn/yun/72410.html
摘要:題目解答這一題其實(shí)挺的,如果說第一道題的關(guān)鍵是記錄層次,那么這一題的關(guān)鍵是把這一層的傳到下一層去,代碼如下關(guān)鍵點(diǎn)在于把上一層的傳到下一層去,這樣的話,接下來還有幾層,每一層都會(huì)加上這個(gè)也就等于乘以了它的層數(shù) 題目:Given a nested list of integers, return the sum of all integers in the list weighted by...
摘要:返回的是表示是否走到了結(jié)尾。起到的就是緩存作用,因?yàn)檎{(diào)用之后馬上就走到下一個(gè)了。如果調(diào)用,返回用得到和最初的輸入相同的做相同的步驟存入不斷拆開得到結(jié)果。思想就是來自括號(hào),后面也會(huì)跟進(jìn)的專題 Iterator其實(shí)就是一個(gè)單鏈表,無法回頭看。java里很多數(shù)據(jù)結(jié)構(gòu)都有這個(gè)接口,使用時(shí)需要initalize,得到一個(gè)iterator. 調(diào)用next()返回的是一個(gè)object, 指向的是下一...
摘要:題目要求假設(shè)有一個(gè)嵌套形式的數(shù)組,要求按照順序遍歷數(shù)組中的元素。思路和代碼首先可以想到通過深度優(yōu)先遞歸的方式將嵌套形式的數(shù)組展開為一個(gè)無嵌套的列表。 題目要求 Given a nested list of integers, implement an iterator to flatten it. Each element is either an integer, or a lis...
摘要:設(shè)計(jì)一個(gè)迭代器,使其能夠遍歷這個(gè)整型列表中的所有整數(shù)。列表中的項(xiàng)或者為一個(gè)整數(shù),或者是另一個(gè)列表。示例輸入輸出解釋通過重復(fù)調(diào)用直到返回,返回的元素的順序應(yīng)該是。 Description Given a nested list of integers, implement an iterator to flatten it. Each element is either an integ...
摘要:首先,根據(jù)迭代器需要不斷返回下一個(gè)元素,確定用堆棧來做。堆棧初始化數(shù)據(jù)結(jié)構(gòu),要先從后向前向堆棧壓入中的元素。在調(diào)用之前,先要用判斷下一個(gè)是還是,并進(jìn)行的操作對(duì)要展開并順序壓入對(duì)直接返回。 Problem Given a nested list of integers, implement an iterator to flatten it. Each element is either...
閱讀 2627·2021-11-22 09:34
閱讀 3228·2021-10-25 09:43
閱讀 2141·2021-10-11 10:59
閱讀 3606·2021-09-22 15:13
閱讀 2479·2021-09-04 16:40
閱讀 554·2019-08-30 15:53
閱讀 3338·2019-08-30 11:13
閱讀 2765·2019-08-29 17:30