#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;
}


發佈了96 篇原創文章 · 獲贊 10 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章