Leetcode c语言-4Sum

Title:

Given an array S of n integers, are there elements abc, 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]
]

这道题和之前的3sum很类似,可以参考3sum解答: http://blog.csdn.net/hahachenchen789/article/details/77966124

只是要比3sum多一个循环即可。这个循环就是循环第四个数字的。


solution:

/**
 * Return an array of arrays of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */

void bubblesort(int* nums, int numsSize) {
    int i,j,tmp;
    int flag=0;
    
    for (i=0;i<numsSize;i++) {
        for (j=0;j<numsSize-1;j++) {
            if(nums[j]>nums[j+1]) {
                tmp=nums[j+1];
                nums[j+1]=nums[j];
                nums[j]=tmp;
                flag=1;
            }
        }
        if (flag==0)
            break;
    }
}
int** fourSum(int* nums, int numsSize, int target, int* returnSize) {
    int **result=(int**)malloc(sizeof(int)*(numsSize*(numsSize-1)*(numsSize-2)*(numsSize-3))/24);
    int i,j;
    int begin, end;
    int m=0;
    int sum;
    
    if (numsSize<4) {
        *returnSize=0;
        return result;
    }
    
    bubblesort(nums,numsSize);
    
    for (i=0;i<numsSize-3;i++) {
        if (i>0 && nums[i]==nums[i-1])
            continue;
        for (j=numsSize-1;j>i+2;j--) {
            if (j<numsSize-1 && nums[j]==nums[j+1])
            continue;
            begin=i+1;
            end=j-1;
            while (begin<end) {
                sum=nums[i]+nums[j]+nums[begin]+nums[end];
                if (sum==target) {
                    result[m]=(int *)malloc(sizeof(int)*4);
                    result[m][0]=nums[i];
                    result[m][1]=nums[j];
                    result[m][2]=nums[begin];
                    result[m][3]=nums[end];
                    m++;
                    begin++;
                    end--;
                    while (begin<end && nums[begin]==nums[begin-1]) begin++;
                    while (begin<end && nums[end]==nums[end+1]) end--;
                }
                else if (sum>target) {
                     end--;
                     while(begin<end && nums[end]==nums[end+1])end--; 
                } 
                else {
                    begin++;
                    while(begin<end && nums[begin]==nums[begin-1])begin++;
                }
                    
            }
        }
    }
    
    *returnSize=m;
    return result;
    
}


posted on 2017-09-17 13:01  sichenzhao  阅读(123)  评论(0编辑  收藏  举报

导航