给定一个列表,该列表中的每个要素要么是个列表,要么是整数。将其变成一个只包含整数的简单列表。
注意事项
如果给定的列表中的要素本身也是一个列表,那么它也可以包含列表。
样例
给定 [1,2,[1,2]]
,返回 [1,2,1,2]
。
给定 [4,[3,[2,[1]]]]
,返回 [4,3,2,1]
。
挑战
请用非递归方法尝试解答这道题。
思路:题目中既然是列表中还可能包含列表,就说明需要多次的循环,而递归函数就是循环 的很好的一个方法,若其中的元素是整型,就直接取出来,若是列表就进行递归。
class Solution {
public:
// @param nestedList a list of NestedInteger
// @return a list of integer
void lflatten(const vector<NestedInteger> &nestedList,vector<int> &result) {
// Write your code here
int i=0;
while(i<nestedList.size()){
if(nestedList[i].isInteger())
result.push_back(nestedList[i++].getInteger());
else
lflatten(nestedList[i++].getList(),result);
}
}
vector<int> flatten(vector<NestedInteger> &nestedList) {
// Write your code here
vector<int> result;
lflatten(nestedList,result);
return result;
}
};
而提高中的要求是非递归算法,其实非递归算法也是要实现循环,每次判断是否是列表,一个一个的进行循环