数组中只出现一次的两个数
剑指 Offer 56 - I. 数组中数字出现的次数
大意:找出数组中只出现一次的两个数(其它出现两次)
时间:O(n),空间:O(1)
class Solution {
public int getLowNoZeroBit(int s) {
int bit = 0;
// 区别于「快速幂」
while(s > 0) {
bit++;
if((s&1) == 1) break;
s >>= 1;
}
return bit;
}
public int[] singleNumbers(int[] nums) {
int xorS = 0;
for(int num : nums) xorS ^= num;
int lowNoZeroBit = getLowNoZeroBit(xorS);
/*
0010
1010
System.out.println(lowNoZeroBit); // 4
*/
int[] ans = new int[2];
for(int num : nums) {
ans[(num >> (lowNoZeroBit-1)) & 1] ^= num;
}
return ans;
}
} </details>
