JZ40 数组中只出现一次的两个数字

本文最后更新于:2022年4月9日 中午

image-20211008111635615

Solution

  • 位运算
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param array int整型vector
* @return int整型vector
*/
vector<int> FindNumsAppearOnce(vector<int>& array) {
// write code here
int x = 0, y = 0, n = 0, m = 1;
// 1.遍历异或
for (int num : array)
n ^= num;
// 2.循环左移,计算 m
while ((n & m) == 0)
m <<= 1;
// 3.遍历分组,array & m != 0; array & m == 0
for (int num : array) {
if (num & m) x ^= num;
else y ^= num;
}
// 5.返回两个数字
if (x <= y)
return vector<int> {x, y};
else
return vector<int> {y, x};
}
};
  • 利用map存储
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
vector<int> FindNumsAppearOnce(vector<int>& array) {
// write code here
vector<int> res;
int n = array.size();
if (n == 0) return res;

unordered_map<int, int> umap;
for (int num : array) {
umap[num]++;
}
for (auto iter = umap.begin(); iter != umap.end(); ++iter) {
if (iter->second == 1) {
res.push_back(iter->first);
}
}
sort(res.begin(), res.end());
return res;
}
};

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!