#22 Flatten List

本文介绍了一种递归方法来解决列表扁平化问题,即如何将嵌套的整数列表转换为简单的一维整数列表。通过具体的代码实现展示了算法的工作原理,并提供了两个实例说明其应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

 This problem is in a contest:  Career Fair Warm Up I . Submit your code and see your ranking!

Given a list, each element in the list can be a list or integer. flatten it into a simply list with integers.

 Notice

If the element in the given list is a list, it can contain list too.

Example

Given [1,2,[1,2]], return [1,2,1,2].

Given [4,[3,[2,[1]]]], return [4,3,2,1].

Challenge 

Do it in non-recursive.

题目思路:

non-recursive我不会做。。下面是我recursive的做法:

Mycode(AC = 489ms):

/**
 * // 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) {
        // Write your code here
        vector<int> ans;
        
        if (nestedList.size() == 0) {
            return ans;
        }
        else {
            for (int i = 0; i < nestedList.size(); i++) {
                if (nestedList[i].isInteger()) {
                    ans.push_back(nestedList[i].getInteger());
                }
                else {
                    vector<NestedInteger> rest = nestedList[i].getList();
                    vector<int> r = flatten(rest);
                    for (int j = 0; j < r.size(); j++) {
                        ans.push_back(r[j]);
                    }
                }
            }
        }
    }
};


### 将 Python 中的二维列表展平为一维列表 在 Python 中,可以采用多种方法来实现将二维列表展平成一维列表的操作。以下是几种常见的方式: #### 使用 List Comprehension 实现展平操作 List comprehension 提供了一个简洁的方式来遍历嵌套结构,并将其元素收集到一个新的列表中。 ```python two_d_list = [[1, 2], [3, 4], [5]] flattened_list = [item for sublist in two_d_list for item in sublist] print(flattened_list) # 输出: [1, 2, 3, 4, 5] ``` 这种方法利用了双重循环机制,在单行代码里完成了从子列表提取项的任务[^1]。 #### 利用 `itertools.chain` 函数 Python 的标准库 itertools 模块提供了 chain 方法,它能够接收多个可迭代对象作为参数并将它们连接起来形成新的单一序列。 ```python from itertools import chain two_d_list = [[7, 8], [9, 10], [11]] result = list(chain(*two_d_list)) print(result) # 输出: [7, 8, 9, 10, 11] # 或者更推荐使用chain.from_iterable()以提高效率和清晰度 result_from_iterable = list(chain.from_iterable(two_d_list)) print(result_from_iterable) # 输出同样结果 ``` 此方式不仅语法更加直观易懂,而且性能上也具有优势[^2]。 #### 应用 sum 函数配合空列表初始化 sum 可以用来累加一系列数值,默认情况下会把整数相加以返回总和;但如果给定初始值为空列表,则它可以有效地拼接所有的子列表成为最终的一维表。 ```python two_d_list = [[12, 13], [], [14, 15, 16]] one_dimensional = sum(two_d_list, []) print(one_dimensional) # 输出: [12, 13, 14, 15, 16] ``` 不过需要注意的是,这种方式虽然简单明了但在处理大型数据集时可能不是最优的选择因为其时间复杂度较高。 #### 处理来自文本文件的数据转换情况 当涉及到从 .txt 文件读取整形数据并构建二维列表后再转为一维的情况时,先按照指定分隔符解析每一行字符串生成相应维度的列表之后再执行上述任一种展平策略即可满足需求[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值