LeetCode 18.4Sum

题目描述

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums 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.

Example:

Given array nums = [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]
]

这个题与LeetCode15基本类似,基本思路还是这样:先对数组元素进行快速排序。然后选两个数字,接着后面用两个指针分别指向剩下数组开始和结束,逐步移向中间求和看和targer是否相等。

代码分析

void quickSort(int* nums, int left, int right)
{
    int l,r,exchange,temp;
    l = left; 
    r = right;
    temp = nums[left];
    if(left>=right){return;}
    while(lwhile(l=temp)
        {
            r--;
        }
        while(lif(lleft] = nums[l];
    nums[l] = temp;
    quickSort(nums,left,l-1);
    quickSort(nums,l+1,right);
}
int** fourSum(int* nums, int numsSize, int target, int* returnSize) {
    printf("%d",nums[-1]);
    quickSort(nums, 0, numsSize-1);
    int **array = NULL;
    int i,j,m,n,sum, count=0;
    if (nums==NULL || numsSize == 0)
        {return NULL;}
    for(int i=0; iif(i>0 && nums[i]==nums[i-1]){continue;}
        for(int j=i+1; jif(nums[j]==nums[j-1] && j>i+1){continue;}
            m = j+1;
            n = numsSize-1;
            while(mif(sum==target)
                {
                    count++;
                    array = (int**)realloc(array,sizeof(int*)*count);
                    array[count-1] = (int*)malloc(sizeof(int)*4);
                    array[count-1][0] = nums[i];
                    array[count-1][1] = nums[j];
                    array[count-1][2] = nums[m];
                    array[count-1][3] = nums[n];
                    while(m1])
                    {
                        m++;
                    }
                    while(m1])
                    {
                        n--;
                    }
                    m++;
                    n--;
                }
                else if(sumelse
                {
                    n--;
                }
            }
        }
    }
    *returnSize = count;
    return array;
}

你可能感兴趣的:(LeetCode 18.4Sum)