题目:找出列表中唯一一个不重复的元素
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 more than 3 numbers.
The tests contain some very huge arrays, so think about performance.
My code:
def find_uniq(arr):
# your code here
length = len(arr)
for i in range(1,length-1):
if arr[i] != arr[i-1] and arr[i] != arr[i+1]: #将元素与相邻的两个元素比较,是否相同
return arr[i]
elif arr[i] != arr[i-1] and arr[i] == arr[i+1]: #不同的元素在列表开头
return arr[i-1]
elif arr[i] == arr[i-1] and arr[i] != arr[i+1]: #不同的元素在列表结尾
return arr[i+1]
else:
pass