查找数组中的最小唯一编号

时间:2012-08-14 01:54:18

标签: algorithm

数组中的最小唯一编号定义为         min{v|v occurs only once in the array} 例如,{1,4,1,2,3}的最小唯一编号是2。 有没有比排序更好的方法?

3 个答案:

答案 0 :(得分:5)

我相信这是时间和空间上的O(N)解决方案:

HashSet seenOnce;     // sufficiently large that access is O(1)
HashSet seenMultiple; // sufficiently large that access is O(1)

for each in input // O(N)
    if item in seenMultiple
        next
    if item in seenOnce
        remove item from seenOnce
        add to item seenMultiple
    else
        add to item seeOnce

smallest = SENTINEL
for each in seenOnce // worst case, O(N)
    if item < smallest
        smallest = item

如果您的积分值范围有限,则可以使用由该值索引的BitArray替换HashSet。

答案 1 :(得分:0)

您无需进行完整排序。执行冒泡排序内循环,直到您在一端获得不同的最小值。在最好的情况下,这将具有时间复杂度O(k * n),其中k =非不同的最小值的数量。然而,最坏情况的复杂性是O(n * n)。因此,当k的预期值<&lt;&lt; Ñ

我认为这将是最小的可能时间复杂度,除非您可以将任何O(n * logn)排序算法适应上述任务。

答案 2 :(得分:0)

使用字典的Python版本。
时间复杂度 O(n) 和空间复杂度 O(n):

from collections import defaultdict
d=defaultdict(int)
for _ in range(int(input())):
    ele=int(input())
    d[ele]+=1
m=9999999
for i in d:
    if d[i]==1 and i<m:
        m=i
print(m if m!= 9999999 else -1)

请告诉我是否有更好的方法。

相关问题