mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
24 lines
717 B
Markdown
24 lines
717 B
Markdown
![]() |
# [136. Single Number](https://leetcode.com/problems/single-number/description/)
|
|||
|
# 思路
|
|||
|
## 思路一
|
|||
|
最常规的思路就是用一个map或者散列(unordered_map)记录是否出现过。
|
|||
|
map: 时间复杂度O(nlogn), 空间复杂度O(n)
|
|||
|
unordered_map: 时间复杂度O(n), 空间复杂度O(N)
|
|||
|
|
|||
|
## 思路二*
|
|||
|
若某个数出现两次,则异或操作后得0,所以可以考虑将数组所有元素进行异或操作,最终得到的值就是欲求值。
|
|||
|
时间复杂度O(n), 空间复杂度O(1), 完美
|
|||
|
# C++
|
|||
|
## 思路二
|
|||
|
```
|
|||
|
class Solution {
|
|||
|
public:
|
|||
|
int singleNumber(vector<int>& nums) {
|
|||
|
int res = 0;
|
|||
|
for(int num: nums) res = res ^ num;
|
|||
|
|
|||
|
return res;
|
|||
|
}
|
|||
|
};
|
|||
|
```
|