您的位置:首页 > 其它

LintCode 平面列表

2017-09-08 19:14 483 查看
1.描述

给定一个列表,该列表中的每个要素要么是个列表,要么是整数。将其变成一个只包含整数的简单列表。

注意事项

如果给定的列表中的要素本身也是一个列表,那么它也可以包含列表。

样例

给定
[1,2,[1,2]]
,返回
[1,2,1,2]


给定
[4,[3,[2,[1]]]]
,返回
[4,3,2,1]


2.分析

对给定列表中的元素依次进行判断,若为整数只要取出即可;若为列表则转而对该列表进行同样的判断提取操作,

对当前小列表操作完后退回大列表继续向后查找。

3.代码

/**

 * // 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> v;

    vector<int> flatten(const vector<NestedInteger> &nestedList) {

        // Write your code here

       int n=nestedList.size();

       for(int i=0;i<n;i++)

            {

                if(nestedList[i].isInteger())

                v.push_back(nestedList[i].getInteger());

                else

                flatten(nestedList[i].getList());

            }

       return v;
    }

};

4.总结

在给定的类定义中有bool isInteger() const;int getInteger() const;const vector<NestedInteger> &getList() const;

根据这些成员函数实际上就提示了需要判断是否只有一个整数并且若不是可以提取出列表继续递归。注意这些成

员函数都有const,因此在flatten函数中的参数也需要const。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: