1. 给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符 (异或又名: 不进位加法)
a + b = (a ^ b) + (a & b << 1)
2. 数组中,只有一个数出现一次,剩下都出现两次,找出出现一次的数
public class Solution {
public int singleNumber(int[] nums) {
int result = 0, n = nums.length;
for (int i = 0; i < n; i++)
{
result ^= nums[i];
}
return result;
}
}
3. 数组中,只有一个数出现一次,剩下都出现三次,找出出现一次的数
Ones,Twos俩个数表示当前位的状态
如果Twos里面ith是1,则ith当前为止出现1的次数除以3的状态是2
如果Ones里面ith是1,则ith目前为止出现1的次数除以3的状态是1
output | input | comments | |||
ones | ones ^ nums[i] | ~twos | ones =(ones ^ nums[i]) & ~twos | twos | |
0 | - | 0 | - | 不一样处候选 | |
1 | 1 | 1 | 0 | 保留 | |
1 | 0 | 0 | 1 | 2+1 = 3 消除 | |
twos | twos ^ nums[i]) | ~ones | twos = (twos ^ nums[i]) & ~ones | ones | comments |
0 | - | 0 | - | 不一样处候选 | |
1 | 1 | 1 | 0 | 1个数非奇数,是偶数, keep | |
1 | 0 | 0 | 1 | 1个数奇数,非偶数, 消除 |
public class Solution {
public int singleNumber(int[] nums) {
int ones = 0, twos = 0;
for(int i = 0; i < nums.length; i++){
ones = (ones ^ nums[i]) & ~twos;
twos = (twos ^ nums[i]) & ~ones;
}
return ones;
}
}
设此两个数为x和y, 对于x和y,一定是其中一个这一位是1,另一个这一位不是1。 对于其他成对出现的元素,要么都在x所在的那个集合,要么在y所在的那个集合。
public class Solution {
public int[] singleNumber(int[] nums) {
//用于记录,区分“两个”数组
int diff = 0;
for(int i = 0; i < nums.length; i ++) {
diff ^= nums[i];
}
//diff & (-diff)就是取diff的最后一位1的位置
diff &= -diff;
int[] rets = {0, 0};
for(int i = 0; i < nums.length; i ++) {
//分属两个“不同”的数组
if ((nums[i] & diff) == 0) {
rets[0] ^= nums[i];
}
else {
rets[1] ^= nums[i];
}
}
return rets;
}
}
5. Maximum XOR of Two Numbers in an Array
int findMaximumXOR(vector<int>& nums) {
int max = 0, mask = 0;
unordered_set<int> t;
// search from left to right, find out for each bit is there
// two numbers that has different value
for (int i = 31; i >= 0; i--){
// mask contains the bits considered so far
mask |= (1 << i);
t.clear();
// store prefix of all number with right i bits discarded
for (int n: nums){
t.insert(mask & n);
}
// now find out if there are two prefix with different i-th bit
// if there is, the new max should be current max with one 1 bit at i-th position, which is candidate
// and the two prefix, say A and B, satisfies:
// A ^ B = candidate
// so we also have A ^ candidate = B or B ^ candidate = A
// thus we can use this method to find out if such A and B exists in the set
int candidate = max | (1<<i);
for (int prefix : t){
if (t.find(prefix ^ candidate) != t.end()){
max = candidate;
break;
}
}
}
return max;
}
Sample:
input | 1010 | 1111 | 0110 | 0011 |
output | 1100 | |||
init | 0 | [] | 0 | |
i | mask | set | candidate | max |
3 | 1000 | 1000 '0000 | 1000 | 1000 |
2 | 1100 | 1000 1100 0100 0011 | 1100 | 1100 |
1 | 1110 | 1010 1110 0110 0010 | 1110 | 1100 |
0 | 1111 | 1010 1111 0110 0011 | 1101 | 1100 |