📅  最后修改于: 2023-12-03 15:07:57.950000             🧑  作者: Mango
在整数数组 nums 中,有 一些 元素重复了若干次,但是数组中只有一个元素是恰好出现 一次 的,其余元素均出现 两次 或者 更多 次。请找出并返回那个只出现了一次的元素。
例如:
输入: nums = [1,2,3,2,1]
输出: 3
最简单的方法就是使用两重循环暴力枚举,时间复杂度为 $O(n^2)$。
def find_single_number(nums):
for i in range(len(nums)):
count = 0
for j in range(len(nums)):
if nums[i] == nums[j]:
count += 1
if count == 1:
return nums[i]
可以使用哈希表来存储每个数字出现的次数,然后遍历哈希表找出仅出现一次的数字,时间复杂度为 $O(n)$。
def find_single_number(nums):
hash_map = {}
for num in nums:
if num in hash_map:
hash_map[num] += 1
else:
hash_map[num] = 1
for num in hash_map:
if hash_map[num] == 1:
return num
异或运算(^)是一种二进制运算符,用于计算两个数每个位上的差异。对于整数 a 和 b,a ^ b 的结果为 1 的位表示 a 和 b 在这个位置上不同。
根据异或运算的性质,将数组中所有的数字进行异或运算,最终的结果即为仅出现一次的数字,时间复杂度为 $O(n)$。
def find_single_number(nums):
result = 0
for num in nums:
result ^= num
return result
以上三种方法均可以解决在允许重复的数组中查找定点的问题。其中第三种方法效率最高,建议使用该方法来解决此问题。