LeetCode解题 15:3Sum
Problem 15: 3Sum [Medium]
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:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
来源:LeetCode
解题思路
- 使用sort()对数组排序。
- 遍历数组,并在当前数字
nums[i]
的后续数字nums[i+1]
~nums[n-1]
中,使用双指针法寻找和为-nums[i]的两个数。 - 在遍历以及双指针移动过程中注意跳过重复的数字。
排序的时间复杂度O(n log n),遍历数组+双指针过程时间复杂度O(n2),总体时间复杂度O(n2)。
要点:排序
、双指针
Solution (Java)
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
Arrays.sort(nums);
int N = nums.length;
if(N < 3) return result;
int last = nums[0];
int left, right, temp;
for(int i = 0; i < N-2; i++){
if(nums[i] > 0) break;
if(nums[i] == last && i > 0) continue;
last = nums[i];
left = i+1;
right = N-1;
while(left < right){
if(nums[i] + nums[left] + nums[right] == 0){
result.add(Arrays.asList(nums[i], nums[left], nums[right]));
temp = nums[left];
while(++left < right && nums[left] == temp);
}
else if(nums[i] + nums[left] + nums[right] > 0){
temp = nums[right];
while(--right > left && nums[right] == temp);
}
else{
temp = nums[left];
while(++left < right && nums[left] == temp);
}
}
}
return result;
}
}
修改过程
- 考虑N<3的情况直接返回空。
- 遍历数组的当前数字
nums[i]
若大于0,则后续的数字之和不会小于0(因为已从小到大排序),不可能出现三个数总和为0的情况,因此可直接跳出循环。 - 在双指针移动过程中同样需要考虑跳过重复数字。