LeetCode 136. 只出现一次的数字

题目描述

136. 只出现一次的数字

image-20250420073851591

思路分析

异或运算

image-20250508003938709

参考代码

1
2
3
4
5
6
7
func singleNumber(nums []int) int {
	res := 0
	for _, num := range nums {
		res ^= num
	}
	return res
}
  • 时间复杂度:O(n),需要遍历整个数组一次。
  • 空间复杂度:O(1),只使用了常数级别的额外空间。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
func singleNumber(nums []int) int {
	seen := map[int]struct{}{}
	for _, cur := range nums {
		if _, exists := seen[cur]; exists {
			delete(seen, cur)
		} else {
			seen[cur] = struct{}{}
		}
	}
	for key := range seen {
		return key
	}
	return 0
}
  • 时间复杂度:O(n),需要遍历整个数组一次。
  • 空间复杂度:O(n),使用了一个哈希集合来存储元素。

➡️ 点击查看 Java 题解

1
write your code here
本文作者:
本文链接: https://hgnulb.github.io/blog/2025/84719035
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!