zoukankan      html  css  js  c++  java
  • 【python-leetcode448-循环排序】找到所有数组中消失的数字

    问题描述:

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

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

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

    示例:

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

    输出:
    [5,6]

    核心;循环排序法,让每个数字在其应该的位置上。注意数值和下标之间的关系

    class Solution:
        def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
            res=[]
            l=0
            r=len(nums)-1
            while l<=r:
                if nums[l] != nums[nums[l]-1]:
                    nums[nums[l]-1],nums[l] = nums[l],nums[nums[l]-1]
                else:
                    l+=1
            for i in range(len(nums)):
                if i+1 != nums[i]:
                    res.append(i+1)
            return res

    比如:nums=[4,3,2,7,8,2,3,1]

    过程:

    [7,3,2,4,8,2,3,1]

    [3,3,2,4,8,2,7,1]

    [2,3,3,4,8,2,7,1]

    [3,2,3,4,8,2,7,1]

    [2,3,3,4,8,2,7,1]

    [2,3,3,4,1,2,7,8]

    [1,3,3,4,2,2,7,8]

    [1,2,3,4,3,2,7,8]

    最后再遍历一次数组:值!=下标+1,将下标+1加入到结果中。

    结果:

  • 相关阅读:
    Boostrap响应式与非响应式
    Linux文件处理命令
    Linux各目录作用
    linux系统安装
    并发编程之基础( 五)
    Extjs自定义验证介绍
    javascrict中innerhtml和innerText的关系
    List泛型的应用
    winform项目改项目名称
    math.random用法
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12358903.html
Copyright © 2011-2022 走看看