#15 3Sum

题目链接:https://leetcode.com/problems/3sum/


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:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • 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)


/**
 * Return an array of arrays of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
void Sort(int *data,int n) {<span style="white-space:pre">			</span>//归并排序非递归方式实现
	int *tmp = (int *)malloc(n * sizeof(int));
	int lBegin,lEnd,rBegin,rEnd;
	int i,j,k;
	int len = 1;
	while (len < n) {
		lBegin = 0;
		lEnd = len - 1;
		rBegin = len;
		while (rBegin < n) {
			rEnd = lEnd + len < n - 1 ? lEnd + len : n - 1;
			i = lBegin,j = rBegin,k = lBegin;
			while (i <= lEnd && j <= rEnd) {
				if (data[i] <= data[j])
					tmp[k++] = data[i++];
				else
					tmp[k++] = data[j++];
			}
			while (i <= lEnd)
				tmp[k++] = data[i++];
			while (j <= rEnd)
				tmp[k++] = data[j++];
			for (i = lBegin; i <= rEnd; ++i)
				data[i] = tmp[i];
			lBegin += 2 * len;
			lEnd += 2 * len;
			rBegin += 2 * len;
		}
		len *= 2;
	}
	free(tmp);
}

int** threeSum(int* nums,int numsSize,int* returnSize) {
	int i,j,k;
	int **ret = (int **)malloc(sizeof(int *) * 200);
	for (i = 0; i < 200; ++i)
		ret[i] = (int *)malloc(sizeof(int) * 3);
	*returnSize = 0;
	Sort(nums,numsSize);<span style="white-space:pre">		</span>//排序
	for (i = 0; i < numsSize; ++i) {<span style="white-space:pre">		</span>//每趟固定第一个数字,另外两个数分别从生下数列的头和尾向中间逼近
	    if(i > 0 && nums[i] == nums[i - 1])<span style="white-space:pre">		</span>//第一个数相等,之后所求解会与上一趟所求解重合,直接跳过
	        continue;
		j = i + 1;<span style="white-space:pre">				</span>//第二个数从小变大
		k = numsSize - 1;<span style="white-space:pre">			</span>//第三个数从大变小
		while (j < k) {
			if (nums[i] + nums[j] + nums[k] < 0)<span style="white-space:pre">	</span>//和小于0,需要增大sum,即第二个数向右移动从而增大
				++j;
			else if (nums[i] + nums[j] + nums[k] > 0)<span style="white-space:pre">	</span>//和大于0,第三个数向左移动
				--k;
			else {
				if (*returnSize == 0 || ret[*returnSize - 1][0] != nums[i] || ret[*returnSize - 1][1] != nums[j] || ret[*returnSize - 1][2] != nums[k]) {<span style="white-space:pre">				</span>//取出重复解。 因为数组排过序,重复解只可能与上一个解相同,只需要比较上一次所求解
					ret[*returnSize][0] = nums[i];
					ret[*returnSize][1] = nums[j];
					ret[*returnSize][2] = nums[k];
					++*returnSize;
				}
				++j;
				--k;
			}
		}
	}
	return ret;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值