leetcode 3sum提不上去,请看看哪里出问题了

C语言 码拜 7年前 (2017-04-20) 936次浏览
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]
]
本人的代码:

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]
本人从网上找了别人的代码看了一下运行结果,输入上面的数组,输出都是一样的,不知道为什么本人的提交不上去。
leetcode 3sum提不上去,请看看哪里出问题了

解决方案

30

引用:
Quote: 引用:

出错的那组数据,本地调试的时候没有问题吗?

没发现问题,本人直接把结果打印出来了。

试了一下,确实如你所说,本地运行没有问题。目测是未定义行为引起的不同,好好检查程序吧。顺便感叹一下好久没写 c 程序了。

10

边界条件
输入输出格式
……

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明leetcode 3sum提不上去,请看看哪里出问题了
喜欢 (0)
[1034331897@qq.com]
分享 (0)