给定一个由正整数组成的列表,其中有且仅有一个与其他元素都不相同的数字,请编写一个函数,找出这个与众不同的数字。列表元素总个数是奇数个。
示例:
输入:[1, 1, 2],输出,2
输入: [17, 17, 3, 17, 17, 17, 17],输出:3
题目难度:简单
题目来源:codewars : Find the stray number
def find_stray(nums: list) -> int:
pass
assert find_stray([1, 1, 1, 1, 1, 1, 2]) == 2
assert find_stray([2, 3, 2, 2, 2]) == 3
assert find_stray([3, 2, 2, 2, 2]) == 3
def find_stray(numbers: list) -> int:
for i in numbers:
if numbers.count(i) == 1:
return i
assert find_stray([1, 1, 1, 1, 1, 1, 2]) == 2
assert find_stray([2, 3, 2, 2, 2]) == 3
assert find_stray([3, 2, 2, 2, 2]) == 3
def find_stray(nums: list) -> int:
# 定义一个计数字典
dict_count = dict()
# 遍历列表中的每个数字,并统计出现次数
for num in nums:
# 获取该数字之前在计数字典中统计的次数
# 如果没有被统计过则设置初始值为 0
count = dict_count.get(num, 0)
# 该数字统计次数 +1
dict_count[num] = count + 1
# 在计数字典中找出只出现一次的数字
for k in dict_count:
if dict_count[k] == 1:
return k
assert find_stray([1, 1, 1, 1, 1, 1, 2]) == 2
assert find_stray([2, 3, 2, 2, 2]) == 3
assert find_stray([3, 2, 2, 2, 2]) == 3
public Integer findStray(List<Integer> list) {
Integer res = list.get(0);
for (int i = 1; i < list.size(); i++) {
if (list.get(i) != res) {
return list.get(i);
}
}
return res;
}
@Test
public void testFindStray() {
assert 2 == findStray(Arrays.asList(1, 1, 2));
assert 3 == findStray(Arrays.asList(17, 17, 3, 17, 17, 17, 17));
}
nobugs
2021 年10 月 18 日 01:08
7
def find_stray(nums: list) -> int:
for n in set(nums):
if nums.count(n) == 1:
return n
assert find_stray([1, 1, 1, 1, 1, 1, 2]) == 2
assert find_stray([2, 3, 2, 2, 2]) == 3
assert find_stray([3, 2, 2, 2, 2]) == 3
def find_stray(nums: list) -> int:
return [item for item in list(set(nums)) if nums.count(item) == 1][0]
assert find_stray([1, 1, 1, 1, 1, 1, 2]) == 2
assert find_stray([2, 3, 2, 2, 2]) == 3
assert find_stray([3, 2, 2, 2, 2]) == 3
def find_stray(nums: list) -> int:
pre = nums[0]
next_ = nums[1]
for i in nums[2:]:
if i == pre and i == next_:
pre = next_
next_ = i
elif i == next_:
return pre
elif i == pre:
return next_
else:
return i
assert find_stray([1, 1, 1, 1, 1, 1, 2]) == 2
assert find_stray([2, 3, 2, 2, 2]) == 3
assert find_stray([3, 2, 2, 2, 2]) == 3
参考题解:
from functools import reduce
def find_stray(nums: list) -> int:
return reduce(lambda x,y:x ^ y, nums)
assert find_stray([1, 1, 1, 1, 1, 1, 2]) == 2
assert find_stray([2, 3, 2, 2, 2]) == 3
assert find_stray([3, 2, 2, 2, 2]) == 3
思路:利用位运算中的异或来操作两个数字,如果相同数字则会得到0,任何数字和0进行异或运算会得到数字自身。因此,使用标准库中的reduce模块,将列表中的所有元素进行归约处理,当所有的相同元素消除得到0后,最终得到与众不同的唯一数字。
lekaixin
(ALe阿乐)
2021 年11 月 2 日 13:40
12
def find_stray(nums: list) -> int:
for i in nums:
if nums.count(i)==1:
return i
assert find_stray([1, 1, 1, 1, 1, 1, 2]) == 2
assert find_stray([2, 3, 2, 2, 2]) == 3
assert find_stray([3, 2, 2, 2, 2]) == 3
def find_stray(nums: list) -> int:
for x in nums:
if nums.count(x)==1:
return x
assert find_stray([1, 1, 1, 1, 1, 1, 2]) == 2
assert find_stray([2, 3, 2, 2, 2]) == 3
assert find_stray([3, 2, 2, 2, 2]) == 3