Details:
Find the unique number
There is an array with some numbers. All numbers are equal except for one. Try to find it!
findUniq([ 1, 1, 1, 2, 1, 1 ]) === 2
findUniq([ 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.
This is the first kata in series:
- Find the unique number (this kata)
- Find the unique string
- Find The Unique
中文大概含义:
找出最少的一个数字,或者说独一无二的数字
我自己的代码如下:
def find_uniq1(arr):
counter = collections.Counter(arr)
count_pair = sorted(counter.items(),key=lambda x:-x[1])
return count_pair.pop()[0]
第一名代码:
def find_uniq(arr):
a, b = set(arr)
return a if arr.count(a) == 1 else b
第四名代码:
def find_uniq2(arr):
s = set(arr)
for e in s:
if arr.count(e) == 1:
return e
- 第一名代码有问题,有点投机取巧的感觉,随便写一个[ 0, 0, 0.55, 0, 0,1,1 ]就无法运行~~
- 第四名代码属于常规写法,最简单的一种.
- 我的代码使用了collection模块,也很简单.
- 这道题难度系数六级
- 天外有天,人外有人~~
网友评论