标签:leetcode array two pointers c
题目链接:https://leetcode.com/problems/3sum/
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:
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; }
标签:leetcode array two pointers c
原文地址:http://blog.csdn.net/ice_camel/article/details/46594063