Leetcode c语言-3Sum

来源:互联网 发布:手机特效魔法软件 编辑:程序博客网 时间:2024/05/13 01:34

Title:


Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.

For example, given array S = [-1, 0, 1, 2, -1, -4],A solution set is:[  [-1, 0, 1],  [-1, -1, 2]]


这道题目意思很容易理解,找到一个字符串中的三个数,三数相加为0,输出所有不重复的数字组合。以字符串数组的形式。


有几个难点:

1.字符串数组的初始化和空间分配。

2.如何降低时间复杂度,暴力解答容易超时。


针对第一个难点,对于字符串数组,可以看做是二维数组,s[][],第一个元素表示行,第二个表示列,也就是每一个子字符串中的第几个字符,比如,s[][]={{1,2,3},{4,5,6}},那么s[1][1]表示的就是5。

因此分配空间时,首先分配一个所有元素的空间,然后当要对每一个子字符串进行写入时,再具体分配子字符串的空间。

比如:

第一行表示为字符串数组result分配总空间。

int** result = (int**)malloc(sizeof(int)*(numsSize*(numsSize-1)*(numsSize-2))/6);  

第二行表示为m行的子字符串分配3个int大小的空间,也就是这一个子字符串最多可以存储三个int大小的数据。
result[m]=(int*)malloc(sizeof(int)*3);  



针对第二个难点,首先要数组元素进行排序,从小到大。然后再对排序后的数组处理。处理方法是选定选定第一个元素,然后从两边往中间推,如果三个元素相加==0,记录下来,然后左右各移一位,判断移位后的数据是否与移位前的相同,如果相同,则再移一位,确保不会重复。 如果元素相加大于0,右边的左移一位,再进行判断,如果小于0,左边的右移一位,再进行判断。


排序算法采用的是冒泡排序。

代码如下:

/** * Return an array of arrays of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). *//*冒泡排序,flag的作用是判断如果发现有一次排序中没有数据交换,说明已经排序完毕,直接跳出*/void bubblesort(int *nums, int numsSize) {    int i,j;    int temp;    int flag=1;        for (i=0;i<numsSize;i++) {        for (j=0;j<numsSize-1;j++) {            if (nums[j+1]<nums[j]) {                temp=nums[j+1];                nums[j+1] = nums[j];                nums[j] = temp;                flag=0;            }        }        if (flag==1)            break;    }}int** threeSum(int* nums, int numsSize, int* returnSize) {    int** result = (int**)malloc(sizeof(int)*(numsSize*(numsSize-1)*(numsSize-2))/6);      int i,j,n;    int m=0;    int begin,end;    int sum;    if (numsSize<3) {        *returnSize=0;         return result;    }        bubblesort(nums,numsSize);    for (i=0;i<numsSize-2;i++) {        if (nums[i]>0)            break;        if (i>0 && nums[i]==nums[i-1])            continue;        begin=i+1;        end = numsSize-1;            while (begin<end) {                if ((nums[i]+nums[begin]+nums[end]) == 0) {                    result[m]=(int*)malloc(sizeof(int)*3);                      result[m][0]=nums[i];                    result[m][1]=nums[begin];                    result[m][2]=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 ((nums[i]+nums[begin]+nums[end]) >0)                    end--;                else                    begin++;            }            }    *returnSize=m;      return result;       }


原创粉丝点击