本文共 4336 字,大约阅读时间需要 14 分钟。
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]]
====== 参考的网上的思想, 自己写了一遍,Leecode还是报 runtime error ,不知道哪里错了, 接着再继续更改 ====
/** * Return an array of arrays of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */int** threeSum(int* nums, int numsSize, int* returnSize) { int** ret; int cnt = 0, left=0, right=0, i , j, tmp=0, sum=0; if (numsSize < 3) return NULL; if (numsSize == 3 ) { if (nums[0]+nums[1]+nums[2] == 0) { printf("hello\n"); ret = (int(*)[3])malloc(sizeof(int*) * 1); *ret=(int *)malloc(sizeof(int)* 3); ret[0][0]=nums[0]; ret[0][1]=nums[1]; ret[0][2]=nums[2]; printf("%d, %d, %d\n", ret[0][0], ret[0][1], ret[0][2]); *returnSize=numsSize; printf("%d", *returnSize); return ret; } else { return NULL; } } int *num1=malloc(sizeof(int) * numsSize *10); int *num2=malloc(sizeof(int) * numsSize *10); int *num3=malloc(sizeof(int) * numsSize *10); memset(num1, 0 , numsSize); memset(num2, 0 , numsSize); memset(num3, 0 , numsSize); for (i=0;inums[j]) { tmp=nums[i]; nums[i]=nums[j]; nums[j]=tmp; } } } for(i = 0; i < numsSize - 2; i++){ left = i + 1; right = numsSize - 1; while(left < right){ sum = nums[i] + nums[left] + nums[right]; // 如果三个数的和大于等于目标数,那将尾指针向左移 if(sum > 0) { right--; // 如果三个数的和小于目标数,那将头指针向右移 } else { if (sum < 0) { left++; } else { num1[cnt]=nums[i]; num2[cnt]=nums[left]; num3[cnt]=nums[right]; printf("%d,%d,%d====\n", num1[cnt], num2[cnt], num3[cnt]); cnt++; left++; right--; break; } } } } if (cnt==0) return NULL; ret = (int** )malloc( numsSize *2 * sizeof(int*)); for (i=0; i < cnt; i++){ ret[i]=malloc(sizeof(int) * 3); } printf("%d\n", cnt); for (i=0; i
==================== 更改后, leetcode accept ======================
/** * Return an array of arrays of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */int** threeSum(int* nums, int numsSize, int* returnSize) { int** ret; int cnt = 0, left=0, right=0, i , j, tmp=0, sum=0, is_exist=0, p=0, q=0; if (numsSize < 3) return NULL; int *num1=malloc(sizeof(int) * numsSize *20); int *num2=malloc(sizeof(int) * numsSize *20); int *num3=malloc(sizeof(int) * numsSize *20); memset(num1, 0 , numsSize); memset(num2, 0 , numsSize); memset(num3, 0 , numsSize); for (i=0;inums[j]) { tmp=nums[i]; nums[i]=nums[j]; nums[j]=tmp; } } } for(i = 0; i < numsSize - 2; i++){ left = i + 1; right = numsSize - 1; while(left < right){ sum = nums[i] + nums[left] + nums[right]; // 如果三个数的和大于等于目标数,那将尾指针向左移 if(sum > 0) { right--; // 如果三个数的和小于目标数,那将头指针向右移 } else { if (sum < 0) { left++; } else { is_exist=0; for (p=0; p
转载地址:http://aoxkb.baihongyu.com/