leetCode-0015_三数之和


题目描述

英文题目

Given an array nums of n integers, are there elements a, b, c in nums 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.

Example:

1
2
3
4
5
6
7
Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
中文题目

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

1
2
3
4
5
6
7
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]

解决方法

方法一
  • 描述

我们对原数组进行排序,然后开始遍历排序后的数组,这里注意不是遍历到最后一个停止,而是到倒数第三个就可以了。这里我们可以先做个剪枝优化,就是当遍历到正数的时候就break,为啥呢,因为我们的数组现在是有序的了,如果第一个要fix的数就是正数了,那么后面的数字就都是正数,就永远不会出现和为0的情况了。然后我们还要加上重复就跳过的处理,处理方法是从第二个数开始,如果和前面的数字相等,就跳过,因为我们不想把相同的数字fix两次。对于遍历到的数,用0减去这个fix的数得到一个target,然后只需要再之后找到两个数之和等于target即可。我们用两个指针分别指向fix数字之后开始的数组首尾两个数,如果两个数和正好为target,则将这两个数和fix的数一起存入结果中。然后就是跳过重复数字的步骤了,两个指针都需要检测重复数字。如果两数之和小于target,则我们将左边那个指针i右移一位,使得指向的数字增大一些。同理,如果两数之和大于target,则我们将右边那个指针j左移一位,使得指向的数字减小一些

  • 源码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <stdlib.h>

/**
* Return an array of arrays of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int compare(const void *a, const void *b)
{
return *(int *)a - *(int *)b;
}

//计算两数之和在i和j之内等于target
void two_sum(int *nums, int i, int j, int target, int **results, int *count) {
while (i < j) {
int diff = target - nums[i];
if (diff < nums[j]) {
while (--j > i && nums[j] == nums[j + 1]) {}
} else if (diff > nums[j]) {
while (++i < j && nums[i] == nums[i - 1]) {}
} else {
results[*count] = malloc(3 * sizeof(int));
results[*count][0] = -target;
results[*count][1] = nums[i];
results[*count][2] = nums[j];
(*count)++;

while (++i < j && nums[i] == nums[i - 1]) {}
while (--j > i && nums[j] == nums[j + 1]) {}
}
}
}

//计算三数之和
int** threeSum(int* nums, int numsSize, int* returnSize) {
if (numsSize < 3) {
return NULL;
}

qsort(nums, numsSize, sizeof(*nums), compare);

*returnSize = 0;
int **results = malloc(sizeof(int *) * (((numsSize * (numsSize - 1) * (numsSize - 2))) / (3 * 2 * 1)));
for (int i = 0; i < numsSize; i++) {
if (i == 0 || i > 0 && nums[i] != nums[i - 1]) {
//加上大于0判断,优化
two_sum(nums, i + 1, numsSize - 1, -nums[i], results, returnSize);
}
}

return results;
}
void test()
{
// int arr[6] = { -1, 0, 1, 2, -1, -4 };
int arr[4] = { 1, 2, -2, -1 };
int count = 0;
int **ret = threeSum(arr, 4, &count);

if (ret) {
for (int i = 0; i < count; i++) {
int *temp = ret[i];
printf("%d->%d->%d\n",temp[0],temp[1],temp[2]);
}

}
}

题目来源

3Sum

三数之和