Given an array nums
of n integers, are there elements a, b, c in nums
such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
Solution
static int cmp(const void* a, const void* b) {
return *(int*) a - *(int*) b;
}
int** threeSum(int* nums, int numsSize, int* returnSize) {
if (numsSize < 3) return NULL;
int** ans = calloc(20480, sizeof(int*));
int i = 0, j, k, remain;
(*returnSize) = 0;
qsort(nums, numsSize, sizeof(int), cmp);
for (i = 0; i < numsSize - 2; i++) {
// remove duplicates
if (i == 0 || i > 0 && nums[i] != nums[i - 1]) {
j = i + 1;
k = numsSize - 1;
remain = 0 - nums[i];
while (j < k) {
if (nums[j] + nums[k] == remain) {
ans[*returnSize] = calloc(3, sizeof(int));
ans[*returnSize][0] = nums[i];
ans[*returnSize][1] = nums[j];
ans[*returnSize][2] = nums[k];
(*returnSize)++;
// remove duplicates
while (j < k && nums[j] == nums[j+1]) j++;
while (j < k && nums[k] == nums[k-1]) k--;
j++;
k--;
} else if (nums[j] + nums[k] < remain) {
j++;
} else {
k--;
}
}
}
}
return ans;
}