There is an array with some numbers. All numbers are equal except for one. Try to find it!
find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2
find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55
It’s guaranteed that array contains at least 3 numbers.
The tests contain some very huge arrays, so think about performance.
我的解决方案:
def find_uniq(arr):
arr.sort()
return arr[0] if arr[0]!=arr[1] else arr[-1]
再看看别人的
def find_uniq(arr):
i = iter(arr)
a, b, c = next(i), next(i), next(i)
if a != b:
return a if b == c else b
else:
while c == a:
c = next(i)
return c
这个思路很巧妙,先前三个比,如果它们一样,进入while循环之中,如果c==a那就可以一直循环下去,如果不一样,说明那个数字找到了,返回就行。