重复数组中找出所有消失的数字

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

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

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

示例:

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

输出:
[5,6]

来源:力扣(LeetCode)


原理类似的blog:

0~n-1缺失的数字

消失的两个数字(Python)

错误的数字集合

不同的是:本题中,数组长度和预期原数组是一样的。略作修改第2篇blog博客的代码即可。


# -*- coding: utf-8 -*-
#!/usr/bin/env python

"""
Created on Tue Jul 28 22:41:33 2020

@author: MRN_6

@github: https://github.com/WowlNAN

@blog: https://blog.csdn.net/qq_21264377

"""


def a(nums):
    if nums==None or nums==[]:
            return []
    a=nums
    a=sorted(a)
    l=len(a)
    n=l
    print(a)
    i=1
    j=1
    b=[]
    while i<=n and j<=l:
        #print(i, a[j-1])
        if i==a[j-1]:
            i+=1
            j+=1    
        elif i<a[j-1]:
            b.append(i)
            i+=1
        else:
            j+=1
    #print(i,j)
    while i<=n:
        b.append(i)
        i+=1
    return b

print(a([4,3,2,6,8,2,3,1]))

猜你喜欢

转载自blog.csdn.net/qq_21264377/article/details/107647725