leetcode-15-three-sum

Description

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]
]

####

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
/**
* @note leetcode-三数之和为0
* @apiNote 思路为 先排序, 然后有两个指针 head和end。 要计算的第一个数一定是负数,所以只要后两个数相加等于
* 0-第一个数 即可。
* @since 19-8-26 10:27 by jdk 1.8
*/
public class ThreeSum {

private static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
//进行排序
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0) {
return result;
}
//之前的相等,我选择跳过
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int header = i + 1;
int end = nums.length - 1;
int val = 0 - nums[i];
while (header < end) {
if (nums[header] + nums[end] == val) {
List<Integer> list = Arrays.asList(nums[i], nums[header], nums[end]);
result.add(list);
while (header < end && nums[end] == nums[end - 1]) end--;
while (header < end && nums[header] == nums[header + 1]) header++;
end--;
header++;
} else if (nums[header] + nums[end] > val) {
end--;
} else {
header++;
}
}
}


return result;
}

public static void main(String[] args) {
int[] nums = {};
List<List<Integer>> lists = threeSum(nums);
System.out.println(lists);

}
}

####

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
# O(n * n)
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
nums.sort() # 排序
for i in xrange(0, len(nums) - 2):
# 如果与前一个值相同,则跳过
# 避免重复计算
if i > 0 and nums[i] == nums[i-1]:
continue
l, r = i + 1, len(nums) - 1
while l < r:
s = nums[i] + nums[l] + nums[r]
if s < 0:
# 和过小,增大 nums[l]
l += 1
elif s > 0:
# 值过大,减小 nums[r]
r -= 1
else:
# 存储目标结果
res.append((nums[i], nums[l], nums[r]))
# 避免 l,r 重复计算
while l < r and nums[l] == nums[l + 1]:
l += 1
while l < r and nums[r] == nums[r - 1]:
r -= 1
# 下一组目标值
l += 1
r -= 1
return res
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×