15. 3Sum (重新分配数组大小)
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
/** * Return an array of arrays of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */ int** threeSum(int* nums, int numsSize, int* returnSize) { int target; int i = 0, j, k; int *solutionSet; //element in the returnArray int** returnArray = NULL; int size = 0; //size of returnArray quickSort(nums, 0, numsSize-1); for(; i < numsSize-2; i++){ //最外层遍历每个元素 target = 0 - nums[i]; //里层: Two Sum j = i+1; k = numsSize-1; while(j<k){ if(nums[j]+nums[k] < target) j++; else if(nums[j]+nums[k] > target) k--; else{ solutionSet = malloc(sizeof(int)*3); solutionSet[0] = nums[i]; solutionSet[1] = nums[j]; solutionSet[2] = nums[k]; j++; k--; size++; returnArray = realloc(returnArray,size*sizeof(solutionSet)); returnArray[size-1] = solutionSet; while(j<k && nums[j]==nums[j-1]) j++; //To avoid duplicate triplets while(j<k && nums[k]==nums[k+1]) k--; } } while(i<numsSize-3 && nums[i]==nums[i+1]) i++;//To avoid duplicate triplets } *returnSize = size; return returnArray; } void quickSort(int* nums, int start, int end){ int p1 = start+1; int p2 = end; int tmp; while(p1 <= p2){ while(p1 <= p2 && nums[p1] <= nums[start]){ p1++; } while(p1 <= p2 && nums[p2] > nums[start]){ p2--; } if(p1 < p2){ tmp = nums[p1]; nums[p1] = nums[p2]; nums[p2] = tmp; p1++; p2--; } } //put the sentinel at the end of the first subarray if(start!=p2){ tmp = nums[start]; nums[start] = nums[p2]; nums[p2] = tmp; } if(start < p2-1) quickSort(nums,start, p2-1); //sort first subarray (<=sentinel) if(p1 < end) quickSort(nums,p1, end); //sort second subarray (>sentinel) }