15. 三数之和
作者:互联网
15. 三数之和
难度中等给你一个包含 n
个整数的数组 nums
,判断 nums
中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0
且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例 1:
输入:nums = [-1,0,1,2,-1,-4] 输出:[[-1,-1,2],[-1,0,1]]
示例 2:
输入:nums = [] 输出:[]
示例 3:
输入:nums = [0] 输出:[]
提示:
0 <= nums.length <= 3000
-105 <= nums[i] <= 105
我的解法:暴力,但会超时 315/318,
就这破算法也写了3个小时,丑的不忍直视。去重耗时间
/** * Return an array of arrays of size *returnSize. * The sizes of the arrays are returned as *returnColumnSizes array. * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). */ int cmp(const void*a, const void*b){ return *(int*)a - *(int*)b; }int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){ int i = 0; int j = 0; int k = 0; int m = 0; int sum = 0; int arr[3000][3] = {0}; int cnt = 0; int tmp = 0; int** res = NULL; if(!nums){ return res; }
qsort(nums, numsSize,sizeof(nums[0]),cmp);//排序 for(i=0; i<numsSize; i++){ for(j=i+1; j<numsSize; j++){ for(k = j+1;k<numsSize;k++){ tmp = nums[i]+nums[j]+nums[k]; if(tmp == 0){ arr[cnt][0] = nums[i]; arr[cnt][1] = nums[j]; arr[cnt][2] = nums[k]; cnt++; for(m =0;m<cnt-1;m++){ //for循环去重,用最新添加的一组和前面的cnt -2组对比, if(arr[m][0]==nums[i]&& arr[m][1] == nums[j]){ //对比前两个数,如果相同,就将cnt-- ,最新添加的那组不算 cnt--; } } } } }
} *returnSize = cnt; *returnColumnSizes = malloc(cnt*sizeof(int)); res = (int**)malloc(cnt*sizeof(int*)); for(i=0;i<cnt;i++){ (*returnColumnSizes)[i] = 3; res[i] = malloc(3*sizeof(int)); res[i][0] = arr[i][0]; res[i][1] = arr[i][1]; res[i][2] = arr[i][2]; } return res; }
官方解法: 双指针
/** * Return an array of arrays of size *returnSize. * The sizes of the arrays are returned as *returnColumnSizes array. * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). */ int cmp(const void*a, const void*b){ return *(int*)a - *(int*)b; }int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){ int i = 0; int l = 1; int r = numsSize -1; int m = 0; int sum = 0; int arr[20000][3] = {0}; int cnt = 0; int target = 0; int** res = NULL; if(!nums){ return res; }
qsort(nums, numsSize,sizeof(nums[0]),cmp); for(i=0; i<numsSize; i++){ if(i>0 && nums[i] == nums[i-1]){ continue; } target = 0-nums[i]; l = i+1; r = numsSize-1; while(l<r){ sum = nums[l]+nums[r]; if(sum == target){ arr[cnt][0] = nums[i]; arr[cnt][1] = nums[l]; arr[cnt][2] = nums[r]; cnt++; while(l<r && nums[l]==nums[l+1]){ l++; } l++; while(l<r && nums[r]==nums[r-1]){ r--; } r--; }else if(sum>target){ r--; }else { l++; } } }
*returnSize = cnt; *returnColumnSizes = malloc(cnt*sizeof(int)); res = (int**)malloc(cnt*sizeof(int*)); for(i=0;i<cnt;i++){ (*returnColumnSizes)[i] = 3; res[i] = malloc(3*sizeof(int)); res[i][0] = arr[i][0]; res[i][1] = arr[i][1]; res[i][2] = arr[i][2]; } return res; }
标签:numsSize,cnt,15,nums,int,三数,returnColumnSizes,array 来源: https://www.cnblogs.com/xiaomingjun/p/16107353.html