Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added leetcode setmismatch #91

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions setmismatch.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
#include <stdio.h>
#include <stdlib.h>

int* findErrorNums(int* nums, int numsSize, int* returnSize) {
int xr = 0; // Initialize a variable to store the XOR result.

for (int i = 0; i < numsSize; i++) {
xr ^= nums[i]; // XOR all elements in the nums array.
xr ^= (i + 1); // XOR with expected values (1 to n).
}

int idx = 0;

// Find the rightmost set bit (indicated by 'idx') in the XOR result.
while (1) {
if (xr & (1 << idx)) break;
idx++;
}

// Initialize variables for the first and second numbers to be found.
int f = 0;

for (int i = 0; i < numsSize; i++) {
if (nums[i] & (1 << idx)) f ^= nums[i]; // XOR elements with the same set bit as idx.
int x = i + 1;
if (x & (1 << idx)) f ^= x; // XOR expected values with the same set bit as idx.
}

int s = xr ^ f; // Calculate the second number.

// Check if 'f' already exists in the nums array.
int flag = 0;
for (int i = 0; i < numsSize; i++) {
if (nums[i] == f) {
flag = 1;
break;
}
}

*returnSize = 2;

int* result = (int*)malloc(2 * sizeof(int));
if (flag) {
result[0] = f;
result[1] = s;
} else {
result[0] = s;
result[1] = f;
}

return result;
}

int main() {
int nums[] = {1, 2, 2, 4};
int numsSize = sizeof(nums) / sizeof(nums[0]);
int returnSize;
int* result = findErrorNums(nums, numsSize, &returnSize);

printf("Result: [%d, %d]\n", result[0], result[1]);
free(result);

return 0;
}