zoukankan      html  css  js  c++  java
  • lintcode- 22.平面表

    • 题目描述

    22. 平面列表

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

    样例

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

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

    挑战

    请用非递归方法尝试解答这道题。

    • 分析

    由于最近在学习递归问题,所以仍用递归解决的此问题。用Python3 自带isinstance函数判断list元素类型,如果元素为int型,则直接记录,若为list型,则将此元素进入递归循环继续判断。

    • code
    class Solution(object):
    
        # @param nestedList a list, each element in the list
        # can be a list or integer, for example [1,2,[1,2]]
        # @return {int[]} a list of integer
        def flatten(self, nestedList):
            # Write your code here
            if not isinstance(nestedList,list):#这里主要是防止系统直接用int型元素测试代码
                return [nestedList]
            res_list = []
            self.searchList(res_list,nestedList)
            return res_list
    
        def searchList(self,res_List,List):
            for i in List:
                if isinstance(i, int):
                    res_List.append(i)
                elif isinstance(i, list):
                    self.searchList(res_List,i)
            
    

      

  • 相关阅读:
    Array.sort源码
    Linkedlist源码
    最大公约数 2.7
    腾讯笔试题
    腾讯2014校园招聘笔试题
    指针问题
    JavaScript 日历
    QT 初阶 第二章 创建对话框(查找对话框实例)
    QT 初阶 1.3 节 控件的几何排列
    “项目中的问题”
  • 原文地址:https://www.cnblogs.com/yeshengCqupt/p/9928116.html
Copyright © 2011-2022 走看看