zoukankan      html  css  js  c++  java
  • 算法15-----找到所有数组中消失的数字

    1、题目:

    给定一个范围在  1 ≤ a[i] ≤ nn = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。

    找到所有在 [1, n] 范围之间没有出现在数组中的数字。

    您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。

    示例:

    输入:
    [4,3,2,7,8,2,3,1]
    
    输出:
    [5,6]

    2、代码:将该值对应到索引下,索引值变为负数,最后为整数的索引为所求。

        def findDisappearedNumbers(self, nums):
            """
            :type nums: List[int]
            :rtype: List[int]
            """
            """
    
            [-4, -3, -2, -7, 8, 2, -3, -1]
                                                 ^
            """
            
            for x in nums:
                if nums[abs(x)-1] > 0:
                    nums[abs(x)-1] *= -1
            
            ans = []
    
            for i in range(len(nums)):
                if nums[i] > 0:
                    ans.append(i+1)
            return ans

     3、用集合来求

    def findDisappearedNumbers(self, nums):
        return list(set(list(range(1,len(nums)+1)))-set(nums))
  • 相关阅读:
    STA分析(四) lib model
    STA分析(三) cmos模型
    STA分析(二) multi_cycle and false
    STA分析(一) setup and hold
    UVM环境(一)
    Perl中的正则表达式(五)
    RVDS编译器
    ARM的Trust Zone技术
    001-shell基础,创建,运行
    006-mac下finder操作
  • 原文地址:https://www.cnblogs.com/Lee-yl/p/9020111.html
Copyright © 2011-2022 走看看