简体   繁体   English

如何在不使用另一个数组的情况下从数组中删除重复项?

[英]How can I remove duplicates from array without using another array?

I have found this question in a interview我在一次采访中发现了这个问题

I have array我有数组

a = [0,0,1,1,1,2,2,3,4]

I have a sorted array and I want to remove the duplicates from the given array without using any other array , ie space complexity should be O(1).我有一个排序数组,我想从给定数组中删除重复项而不使用任何其他数组,即空间复杂度应该是 O(1)。 Output should be length of the array without duplicates. Output 应该是没有重复的数组的长度。

Output, Output,

a = [0,1,2,3,4]
length = 5

If you really want this in constant space, you need to be careful not to do anything that will reallocate a new array or a temp array.如果你真的想在常量空间中使用它,你需要小心不要做任何会重新分配新数组或临时数组的事情。 You can do this by simply overwriting the elements at the front of the array and keeping track of the count.您可以通过简单地覆盖数组前面的元素并跟踪计数来做到这一点。 At the end, the solution will be the front slice of the array from 0 to count :最后,解决方案将是从0count的数组的前切片:

a = [0,0,1,1,1,2,2,3,4]

current = None
count = 0

for n in a:
    if n != current:
        a[count] = n
        count+=1
        current = n

a[:count]  
# [0, 1, 2, 3, 4]

This will be linear time and constant space.这将是线性时间和恒定空间。

This approach isn't at all time-efficient, but it meets your criteria for space:这种方法一点都不省时,但它符合您的空间标准:

>>> a = [0,0,1,1,1,2,2,3,4]
>>> while any(a.count(x) > 1 for x in a):
...     for x in a:
...         if a.count(x) > 1:
...             x = a.pop(x)
...             break
...
>>> a
[0, 1, 2, 3, 4]

The generally recommended way of doing this is of course:通常推荐的方法当然是:

a = list(set(a))
def duplicate_remover(input_array):
    for item in input_array:
        while input_array.count(item) > 1:
            input_array.remove(item)
    return input_array

my_array = [0,0,0,0,0,1,1,2,2,2,3,3,3,4,5,6]
print(duplicate_remover(my_array))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM