@
2pang 笔误,笔误
https://leetcode.com/problems/3sum//**
* Return an array of arrays of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int cmp(int *a, int *b){
return *a - *b;
}
int** threeSum(int* nums, int numsSize, int* returnSize) {
int **sum;
int i, l, r, x, t=0;
sum = (int**)malloc(sizeof(int*)*20000);
/**
*这是我原来的分配方式
* sum[0]=(int*)malloc(sizeof(int)*20000*3);
* for(i=1; i<20000; i++)
* sum[i] = sum[0] + i*3;
qsort(nums, numsSize, sizeof(int), cmp);
for(i=0; i<numsSize-2 && nums[i]<=0 ; i++ ){
if( i>0 && nums[i]==nums[i-1] )
continue;
for(l=i+1, r=numsSize-1; l<r; ){
x= nums[i]+nums[l]+nums[r];
if( x==0 ){
//这是 leetcode 默认的分配方式
sum[t] = (int*)malloc(sizeof(int)*3);
sum[t][0] = nums[i];
sum[t][1] = nums[l];
sum[t][2] = nums[r];
t++;
for(r--; r>l && nums[r]==nums[r+1]; r--)
;
for(l++; l<r && nums[l]==nums[l-1]; l++)
;
}
else if( x>0 )
for(r--;r>l && nums[r]==nums[r+1]; r--)
;
else
for(l++; l<r && nums[l]==nums[l-1]; l++)
;
}
}
*returnSize = t;
return sum;
}