aboutsummaryrefslogtreecommitdiff
path: root/single_number3.c
diff options
context:
space:
mode:
authorjack <[email protected]>2024-06-14 13:13:15 -0600
committerjack <[email protected]>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /single_number3.c
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'single_number3.c')
-rw-r--r--single_number3.c42
1 files changed, 42 insertions, 0 deletions
diff --git a/single_number3.c b/single_number3.c
new file mode 100644
index 0000000..16a24bb
--- /dev/null
+++ b/single_number3.c
@@ -0,0 +1,42 @@
+// 260. Single Number III
+#include "leetcode.h"
+
+/*
+ * given an integer array 'nums' in which exactly two elements appear only once
+ * and all the otherelements appear exactly twice. find the two elements that
+ * appear only once. you can return the answer in any order. you must write an
+ * algorithm that runs linear runtime complexity and uses only constant extra
+ * space.
+ */
+
+int *singleNumber(int *nums, int numsSize, int *returnSize) {
+ *returnSize = 2;
+ int *ans = (int *)calloc(2, sizeof(int));
+ long long tmp = 0;
+ for (int i = 0; i < numsSize; i++)
+ tmp ^= nums[i];
+ tmp &= -tmp;
+ for (int i = 0; i < numsSize; i++)
+ if (!(tmp & nums[i]))
+ ans[0] ^= nums[i];
+ else
+ ans[1] ^= nums[i];
+ return ans;
+}
+
+int main() {
+ int n1[] = {1, 2, 1, 3, 2, 5}, n2[] = {-1, 0}, n3[] = {0, 1}, rs1, rs2, rs3;
+ int *sn1 = singleNumber(n1, ARRAY_SIZE(n1), &rs1); // expect: 3 5
+ int *sn2 = singleNumber(n2, ARRAY_SIZE(n2), &rs2); // expect: -1 0
+ int *sn3 = singleNumber(n3, ARRAY_SIZE(n3), &rs3); // expect: 1 0
+ for (int i = 0; i < rs1; i++)
+ printf("%d ", sn1[i]);
+ printf("\n");
+ for (int i = 0; i < rs2; i++)
+ printf("%d ", sn2[i]);
+ printf("\n");
+ for (int i = 0; i < rs3; i++)
+ printf("%d ", sn3[i]);
+ printf("\n");
+ free(sn1), free(sn2), free(sn3);
+}