- Flatten List
中文English
Given a list, each element in the list can be a list or integer. flatten it into a simply list with integers.
Example
Example 1:
Input: [[1,1],2,[1,1]]
Output: [1,1,2,1,1]
Explanation:
flatten it into a simply list with integers.
Example 2:
Input: [1,2,[1,2]]
Output:[1,2,1,2]
Explanation:
flatten it into a simply list with integers.
Example 3:
Input: [4,[3,[2,[1]]]]
Output:[4,3,2,1]
Explanation:
flatten it into a simply list with integers.
Challenge
Do it in non-recursive.
Notice
If the element in the given list is a list, it can contain list too.
解法1:DFS递归
代码如下:
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* class NestedInteger {
* public:
* // Return true if this NestedInteger holds a single integer,
* // rather than a nested list.
* bool isInteger() const;
*
* // Return the single integer that this NestedInteger holds,
* // if it holds a single integer
* // The result is undefined if this NestedInteger holds a nested list
* int getInteger() const;
*
* // Return the nested list that this NestedInteger holds,
* // if it holds a nested list
* // The result is undefined if this NestedInteger holds a single integer
* const vector<NestedInteger> &getList() const;
* };
*/
class Solution {
public:
// @param nestedList a list of NestedInteger
// @return a list of integer
vector<int> flatten(vector<NestedInteger> &nestedList) {
int n = nestedList.size();
vector<int> result;
helper(nestedList, result);
return result;
}
private:
void helper(const vector<NestedInteger> &nestedList, vector<int> &result) {
int n = nestedList.size();
for (int i = 0; i < n; ++i) {
if (nestedList[i].isInteger()) {
result.push_back(nestedList[i].getInteger());
} else {
helper(nestedList[i].getList(), result);
}
}
}
};
解法2:
类似解法1。注意不能直接用
vector tmpRes = flatten(nestedList[i].getList());
因为nestedList[i].getList()返回的是一个临时变量(const?),而flatten函数的参数是用的非const的引用,这是C++不允许的,解释见
https://blog.youkuaiyun.com/lx627776548/article/details/52397294
class Solution {
public:
// @param nestedList a list of NestedInteger
// @return a list of integer
vector<int> flatten(vector<NestedInteger> &nestedList) {
vector<int> result;
for (int i = 0; i < nestedList.size(); ++i) {
if (nestedList[i].isInteger()) {
result.push_back(nestedList[i].getInteger());
} else {
vector<NestedInteger> nestList = nestedList[i].getList();
vector<int> tmpRes = flatten(nestList);
result.insert(result.end(), tmpRes.begin(), tmpRes.end());
}
}
return result;
}
};
代码同步在
https://github.com/luqian2017/Algorithm
本文详细介绍了如何将嵌套的整数列表扁平化为单一的一维整数列表,包括递归和非递归方法。通过三个具体示例,展示了算法的运行过程,并提供了两种不同的C++实现方案。
2004

被折叠的 条评论
为什么被折叠?



