Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
1:给定一个 整形数组S 里面的元素 满足 a+b+C =0 ;
2:满足a<= b <= c 排序
// // 3Sum.c // Algorithms // // Created by TTc on 15/6/12. // Copyright (c) 2015年 TTc. All rights reserved. // #include "3Sum.h" #include <stdlib.h> #include <string.h> /** * 三元素(a,b,c)必须排序。(a≤b≤c) 解集必须不包含重复的三元素。 */ static int cmp(const int*a,const int *b){ return *a - *b; } /** * Return an array of arrays of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */ int** threeSum(int* nums, int numsSize, int* returnSize){ if (numsSize <= 0) return NULL; int total = 64; int size = 0; int i,start,end,sum; int ** result = (int **)malloc(sizeof(int *) * total); for(i = 0 ;i< total; i++){ result[i] = (int *)malloc(sizeof(int)* 3); } qsort(nums, numsSize, sizeof(int), (int(*)(const void *,const void *))cmp); for(i = 0; i < numsSize-2; ++i){ if(i > 0 && nums[i] == nums[i-1]){ continue; } start = i + 1; end = numsSize - 1; while(start < end){ sum = nums[i] + nums[start] + nums[end]; if(sum == 0){ if(size > 0 && result[size-1][0] == nums[i] && result[size-1][1] == nums[start] && result[size-1][2] == nums[end]){ ++start; --end; continue; } result[size][0] = nums[i]; result[size][1] = nums[start]; result[size][2] = nums[end]; size++; if(size == total){ total <<= 1; int t; result = (int **)realloc(result,sizeof(int *) * total); for(t = size; t < total; ++t) result[t] = (int *)malloc(sizeof(int) * 3); } ++start; --end; } else if(sum > 0){ --end; }else{ ++start; } } } *returnSize = size; return result; } void test_3Sum(){ int nums[10] = {-1, 0 ,1 ,2 ,-1, -4}; int * returnSize = NULL; returnSize = malloc(sizeof(int)); int ** result = threeSum(nums, 6, returnSize); printf("returnSize===%d \n",*returnSize); for (int j = 0; j < *returnSize; j++) { for (int i = 0 ; i < 3; i++) { printf("result[%d][%d]===%d \n",j,i,result[0][i]); } } }