标签:
class Solution { public: /** * @param A : An integer array * @return : Two integers */ vector<int> singleNumberIII(vector<int> &A) { // write your code here int a_xor_b = 0; int a = 0; int b = 0; //Get xor result of the two single numbers. //The bit which is 1 indicates at that bit A and B are different //The bit which is 0 indicates at that bit A and B are the same for (int &i : A){ a_xor_b ^= i; } /*** * a_xor_b - 1: From the rightest(last) bit * 1) if the bit is 1, set that bit to 0, and keep the rest unchange and exit. * 2) if the bit is 0, set that bit to 1, and check previous bit until 1) * ~(a_xor_b -1): The changed bit will be changed back, unchanged bit will be changed to opposite. * a_xor_b & ~(a_xor_b -1): 1) unchanged bit will all be set to 0 (now they are different) * 2) changed bit will be kept as original. * The result of this opperation will provide us a number, * which from the right(last), the first 1 will be kept and rest of bits will be set to 0, * comparing with a_xor_b; * eg. a_xor_b = 3(0011), (a_xor_b-1) = 2(0010), ~(a_xor_b-1) = (1101), a_xor_b & ~(a_xor_b -1) = (0001) * a_xor_b = 5(0101), (a_xor_b-1) = 4(0100), ~(a_xor_b-1) = (1011), a_xor_b & ~(a_xor_b -1) = (0001) * a_xor_b = 4(0100), (a_xor_b-1) = 3(0011), ~(a_xor_b-1) = (1100), a_xor_b & ~(a_xor_b -1) = (0100) * a_xor_b = 6(0110), (a_xor_b-1) = 5(0101), ~(a_xor_b-1) = (1010), a_xor_b & ~(a_xor_b -1) = (0010) ***/ int first_different_bit_from_right = a_xor_b & ~(a_xor_b - 1); /*** * Second way: * // Get the last bit where 1 occurs. * int first_different_bit_from_right = x_xor_y & -x_xor_y; * -x = ~x+1. Similar reason. ***/ //Divided the whole array to two groups, //The first group contains the numver which at particular bit, the bit value is 1; //The particular bit is the bit which is the rightest bit that a and b are different. //The second group contains number which at the particular bit, the bit value is 0; //Since at that bit, a and b are different,a and b must assign to different group. //The rest member of each group is even(same number will be sign to same group). //If we XOR each group, the result will be the leftover one single number in each group for(int &i : A){ if (i & first_different_bit_from_right ){ a ^= i; } else { b ^= i; } } return {a, b}; } };
标签:
原文地址:http://www.cnblogs.com/codingEskimo/p/5684175.html