260. Single Number III, 260 single
Given an array of numbersnums
, In which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Givennums = [1, 2, 1, 3, 2, 5]
, Return[3, 5]
.
Note:
The order of the result is not important. So in the above example,[5, 3]
Is also correct.
Your algorithm shocould run in linear runtime complexity. cocould you implement it using only constant space complexity?
1/** 2 * Return an array of size * returnSize. 3 * Note: The returned array must be malloced, assume caller callfree (). 4 */5 int * singleNumber (int * nums, int numsSize, int * returnSize) {6 int flag = 0; 7 int I; 8 int k = 1; 9 int * res; 10 res = (int *) malloc (2 * sizeof (int )); // It Must Be malloc but not pass 11 res [0] = res [1] = 0; 12 for (I = 0; I <numsSize; I ++) // first exclusive or exclusive 2 numbers 13 flag ^ = nums [I]; 14 while (1) 15 {16 if (k & flag) // find the first digit in the binary system that is 1, then the number of the two digits is 1, and the other one is 017 break; 18 k = k <1; 19} 20 for (I = 0; I <numsSize; I ++) 21 {22 if (k & nums [I]) // class all the bitwise of 1, 23 res [0] ^ = nums [I]; // exclusive or outgoing 24 else with this value of 0 // likewise, the number of this digit 1 is 25 res [1] ^ = nums [I]; 26 27} 28 * returnSize = 2; 29 return res; 30}