나는 이렇게 학습한다/Algorithm & SQL

Find the unique number

daco2020 2022. 8. 8. 22:13
반응형

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.

 

 

Solution:

def find_uniq(arr):
    n = arr[0] == arr[-1] and arr[0] or arr[1]
    return [i for i in arr if n != i].pop()

 

 

Other Solution:

def find_uniq(arr):
    a, b = set(arr)
    return a if arr.count(a) == 1 else b

 

def find_uniq(arr):
        return min(set(arr),key=arr.count)

 

from collections import Counter

def find_uniq(arr):
    return next(k for k,v in Counter(arr).items() if v == 1)

 

반응형

'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글

Sum of a sequence  (0) 2022.08.10
Remove anchor from URL  (0) 2022.08.09
Fix string case  (2) 2022.08.07
Factorial  (0) 2022.08.07
Count the Digit  (0) 2022.08.05