Skip to content

Commit efb2683

Browse files
committed
"Single Number III"
1 parent baf989a commit efb2683

File tree

2 files changed

+56
-1
lines changed

2 files changed

+56
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ The `☢` means that you need to have a LeetCode Premium Subscription.
4444
| 264 | [Ugly Number II] | |
4545
| 263 | [Ugly Number] | [C](src/263.c) |
4646
| 261 | [Graph Valid Tree]| |
47-
| 260 | [Single Number III] | |
47+
| 260 | [Single Number III] | [C](src/260.c) |
4848
| 259 | [3Sum Smaller]| |
4949
| 258 | [Add Digits] | [C](src/258.c) |
5050
| 257 | [Binary Tree Paths] | [C++](src/257.cpp) |

src/260.c

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

0 commit comments

Comments
 (0)