LeetCode-15-3Sum(C語言實現)
阿新 • • 發佈:2019-02-12
思路:快排將陣列升序排序,然後選定一個數,夾逼找到另兩個數,依次遍歷,注意邊界條件的設定。
/**
* Return an array of arrays of size *returnSize.* Note: The returned array must be malloced, assume caller calls free().
*/
//快排演算法
void Qsort(int *a, int low, int high){
if(low > high) return;int first = low;
int last = high;
int key = a[first];
while(first < last){
while(first < last && a[last] >= key) --last;
if(first < last) a[first] = a[last];
while(first < last && a[first] <= key) ++first;
if(first < last) a[last] = a[first];
}
a[first] = key;
Qsort(a, low, first-1);
Qsort(a, first+1, high);
}
//k、l、r依次為待分析的第1、2、3個數的下標
//sum記錄當前處理的三個數的和;top記錄棧頂位置
int k, l, r, sum, top = -1;
int **res = (int**)malloc(sizeof(int*) * (numsSize * (numsSize-1) * (numsSize-2)) / 6);
Qsort(nums, 0, numsSize - 1);
//給定陣列不足三個元素,返回為空元素
if(numsSize < 3){
*returnSize = 0;
return res;
}
for(k = 0; k < numsSize - 2; ++k){
//第一個數為正,三個數和必大於零
if(nums[k] > 0) break;
//(邊界處理)跳過重複項
if(k > 0 && nums[k] == nums[k - 1]) continue;
//初始化l和r
l = k + 1;
r = numsSize - 1;
//主迴圈體(夾逼法)
while(l < r){
sum = nums[k] + nums[l] + nums[r];
if(sum == 0){
res[++top] = (int*)malloc(sizeof(int) * 3);
res[top][0] = nums[k];
res[top][1] = nums[l++];
res[top][2] = nums[r--];
//(邊界處理)跳過重複項
while(nums[l] == nums[l - 1]) ++l;
while(nums[r] == nums[r + 1]) --r;
}
else if(sum < 0) ++l;
else --r;
}
}
*returnSize = top + 1;
return res;
}