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

feat: add LeetCode problem 15 #1414

Open
wants to merge 1 commit into
base: master
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
77 changes: 77 additions & 0 deletions leetcode/src/15.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// Function to compare two integers for qsort
// This function is used to sort the array by comparing two integer values.
int compare(const void* a, const void* b) { return (*(int*)a - *(int*)b); }

// Function to find all unique triplets in the array that sum to zero
// This function uses sorting and a two-pointer approach to find triplets
// in a given array that add up to zero, ensuring no duplicate triplets are
// returned. The result is dynamically allocated and returned, along with column
// sizes and the total number of triplets found.
int** threeSum(int* nums, int numsSize, int* returnSize,
int** returnColumnSizes)
{
if (numsSize < 3)
{
*returnSize = 0;
return NULL;
}

// Sort the array
qsort(nums, numsSize, sizeof(int), compare);

int** result = (int**)malloc(numsSize * numsSize * sizeof(int*));
*returnColumnSizes = (int*)malloc(numsSize * sizeof(int));
*returnSize = 0;

// Iterate through each element as the first element of the triplet
for (int i = 0; i < numsSize - 2; ++i)
{
if (i > 0 && nums[i] == nums[i - 1])
{
continue; // Skip duplicates for the first number
}

int left = i + 1;
int right = numsSize - 1;

// Two-pointer approach to find the second and third elements
while (left < right)
{
int sum = nums[i] + nums[left] + nums[right];

if (sum == 0)
{
// Store the triplet
result[*returnSize] = (int*)malloc(3 * sizeof(int));
result[*returnSize][0] = nums[i];
result[*returnSize][1] = nums[left];
result[*returnSize][2] = nums[right];
(*returnColumnSizes)[*returnSize] = 3;
(*returnSize)++;

// Skip duplicates for the second and third numbers
while (left < right && nums[left] == nums[left + 1])
{
left++;
}
while (left < right && nums[right] == nums[right - 1])
{
right--;
}

left++;
right--;
}
else if (sum < 0)
{
left++;
}
else
{
right--;
}
}
}

return result;
}
Loading