Find the unique number

这篇博客探讨了如何在包含至少3个数的数组中找到唯一的不同数值。作者提供了两种解决方案:一种是通过对数组排序后检查首尾元素;另一种则是利用迭代器比较前三项并进入循环寻找。这两种方法都考虑了性能,特别是对于大规模数组的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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那就可以一直循环下去,如果不一样,说明那个数字找到了,返回就行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值