-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path3Sum closet
63 lines (58 loc) · 1.99 KB
/
3Sum closet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
void swap(int *first, int *second){
int temp = *first;
*first = *second;
*second = temp;
}
int partition(int arr[], int lower, int upper){
int i = (lower - 1);
int pivot = arr[upper];
int j;
for(j = lower; j < upper; j++){
if(arr[j] <= pivot){
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[upper]);
return (i + 1);
}
void quickSort(int arr[], int lower, int upper){
if(upper > lower){
int partitionIndex = partition(arr, lower, upper);
quickSort(arr, lower, partitionIndex - 1);
quickSort(arr, partitionIndex + 1, upper);
}
}
int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){
/* Given an integer array nums, returns all the
* triplets [nums[i], nums[j], nums[k]] such that
* i != j, i != k, and j != k,
* and nums[i] + nums[j] + nums[k] == 0. The solution
* set must not contain duplicate triplets. */
*returnSize = 0;
*returnColumnSizes = malloc(numsSize * numsSize * sizeof(int));
int **result = malloc(numsSize * numsSize * sizeof(int*));
quickSort(nums, 0, (numsSize - 1));
int minIdx, maxIdx, check;
int i;
for(i = 0; i < (numsSize - 2); i++){
minIdx = (i + 1), maxIdx = (numsSize - 1);
if((i > 0) && (nums[i] == nums[i - 1])){continue;}
while(minIdx < maxIdx){
check = nums[i] + nums[minIdx] + nums[maxIdx];
if(check < 0){minIdx++;}
else if(check > 0){maxIdx--;}
else{
result[*returnSize] = malloc(3 * sizeof(int));
(*returnColumnSizes)[*returnSize] = 3;
result[*returnSize][0] = nums[i];
result[*returnSize][1] = nums[minIdx];
result[*returnSize][2] = nums[maxIdx];
*returnSize += 1;
minIdx++;
while((nums[minIdx] == nums[minIdx - 1]) && (minIdx < maxIdx)){minIdx++;}
}
}
}
return result;
}