您的位置:首页 > 其它

leetcode (18) - 4Sum

2016-11-06 10:45 465 查看
Given an array S of n integers, are there elements a,
b, c, and d in S such that a + b +
c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note: The solution set must not contain duplicate quadruplets.

For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
[-1,  0, 0, 1],
[-2, -1, 1, 2],
[-2,  0, 0, 2]
]


/**
* Return an array of arrays of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int** fourSum(int* nums, int numsSize, int target, int* returnSize) {
int i, j, left, right, sum=0, cnt=0, length=0,tmp,p=0,flag=0;

if (numsSize<4) return NULL;

int *num1=malloc(sizeof(int) * numsSize *10);
int *num2=malloc(sizeof(int) * numsSize *10);
int *num3=malloc(sizeof(int) * numsSize *10);
int *num4=malloc(sizeof(int) * numsSize *10);

for(i = 0;i<numsSize;i++){
for(j=i+1;j<numsSize;j++){
if (nums[i]>nums[j]){
tmp=nums[i];
nums[i]=nums[j];
nums[j]=tmp;
}
}
}

for (i=0; i<numsSize-1; i++) {
for (j=i+1; j<numsSize-1; j++) {
left=j+1;
right = numsSize-1;
while(left<right){
flag=0;
sum = nums[i]+nums[j]+nums[left]+nums[right];
if (sum >target)
right--;
else {
if (sum < target)
left++;
else {
for(p=0;p<cnt;p++){
if (nums[i]==num1[p] && nums[j]==num2[p] && nums[left]==num3[p] && nums[right]==num4[p])
{
flag=1;
break;
}
}
if(flag==0){
num1[cnt]=nums[i];
num2[cnt]=nums[j];
num3[cnt]=nums[left];
num4[cnt]=nums[right];

cnt++;
}
//break;
left++;
right--;
continue;

}
}
}
}
}

printf("%d\n",cnt);
if (cnt ==0) return NULL;
int** ret = malloc(sizeof(int*) * cnt );
for (i=0;i<cnt;i++) {
ret[i] = malloc(sizeof(int) * 4);
}

for (i = 0; i<cnt; i++)
{
ret[i][0]=num1[i];
ret[i][1]=num2[i];
ret[i][2]=num3[i];
ret[i][3]=num4[i];
}

free(num1);
free(num2);
free(num3);
free(num4);

*returnSize=cnt;
return ret;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: