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.
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]
]
本人的代码:
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]
]
本人的代码:
void sort(int *a, int left, int right) { if(left >= right) { return ; } int i = left; int j = right; int key = a[left]; while(i < j) { while(i < j && key <= a[j]) { j--; } a[i] = a[j]; while(i < j && key >= a[i]) { i++; } a[j] = a[i]; } a[i] = key; sort(a, left, i - 1); sort(a, i + 1, right); } int** threeSum(int* nums, int numsSize, int* returnSize) { sort(nums, 0, numsSize-1); int result = 0; int target = 0; int** rets = (int**)malloc(sizeof(int*)*numsSize); int index = 0; int is_exist = 0; for (int i=0; i< numsSize-2; ++i) { int j = i+1; int k = numsSize - 1; while(j < k){ result = nums[i]+nums[j]+nums[k]; if (result < target) { ++j; }else if (result > target) { --k; }else { for (int p=0; p< index; ++p) { if (rets[p][0] == nums[i]&&rets[p][1] == nums[j]) { is_exist = 1; break; } } if (is_exist == 0) { rets[index] = (int*)malloc(sizeof(int)*3); rets[index][0] = nums[i]; rets[index][1] = nums[j]; rets[index][2] = nums[k]; ++index; } is_exist = 0; --k; } } } *returnSize = index; return rets; }
报错如下:
Submission Result: Runtime Error More Details
Last executed input:
[-7,-4,-6,6,4,-6,-9,-10,-7,5,3,-1,-5,8,-1,-2,-8,-1,5,-3,-5,4,2,-5,-4,4,7]
本人从网上找了别人的代码看了一下运行结果,输入上面的数组,输出都是一样的,不知道为什么本人的提交不上去。
解决方案
30
试了一下,确实如你所说,本地运行没有问题。目测是未定义行为引起的不同,好好检查程序吧。顺便感叹一下好久没写 c 程序了。
10
边界条件
输入输出格式
……
输入输出格式
……