题解 | #只出现一次的牛II#
只出现一次的牛II
https://www.nowcoder.com/practice/fde24d7d8f97467e91403d255243ee1c
#include <vector>
#include <algorithm>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型vector
* @return int整型vector
*/
vector<int> findSingleCowsII(vector<int>& nums) {
// 异或
int xSum = 0;
for (auto num : nums) {
xSum ^= num;
}
// 获得掩码
int mask = getMaskOfHighBit(xSum);
// 根据掩码分成两类
int high = 0, low = 0;
for (auto num : nums) {
if (mask & num)
high ^= num;
else
low ^= num;
}
return {low, high};
}
// 返回最高位的 1 的掩码
int getMaskOfHighBit(int a) {
int ret = 0;
for (int mask = 1; mask > 0; mask <<= 1) {
if ((a & mask) > 0) ret = mask;
}
return ret;
}
};

查看10道真题和解析