forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
260.c
55 lines (44 loc) · 1.08 KB
/
260.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <stdio.h>
#include <stdlib.h>
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* singleNumber(int* nums, int numsSize, int* returnSize) {
if (nums == NULL || returnSize == NULL) return 0;
*returnSize = 2;
int *ans = (int *)calloc(*returnSize, sizeof(int));
int x = 0;
int i;
for (i = 0; i < numsSize; i++) {
x ^= nums[i];
}
/* get first 1 in xor */
int k = 0;
while (((x >> k) & 1) == 0) k++;
/* group numbers in two by k-bit */
int a = 0, b = 0;
for (i = 0; i < numsSize; i++) {
if (nums[i] & (1 << k)) {
a ^= nums[i];
}
else {
b ^= nums[i];
}
}
ans[0] = a;
ans[1] = b;
return ans;
}
int main () {
int nums[] = {1, 2, 1, 3, 2, 5};
int returnSize = 0;
int *ans = singleNumber(nums, sizeof(nums) / sizeof(nums[0]), &returnSize);
int i;
for (i = 0; i < returnSize; i++) {
printf("%d ", ans[i]);
}
printf("\n");
free(ans);
return 0;
}