题目来源:https://leetcode.com/problems/3sum/
问题描述
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]
]
Accepted
490K
Submissions
2.1M
Seen this question in a real interview before?
------------------------------------------------------------
题意
给出一组整数序列,求序列中这样的三个数组成的集合,三个数的和为0.
------------------------------------------------------------
思路
问题可以转化为给定一个数a,求序列中另外两个数b, c,使得b + c = -a.
将输入无序序列排序,对于序列中的每个a,问题转化为求a右侧的数对,使得数对的和为-a. 有序序列求零和数对有经典算法双指针法可以用O(n)解决,这样复杂度是O(n^2)。再加上对输入的无序序列排序的时间O(nlogn),总的复杂度还是O(n^2).
------------------------------------------------------------
代码
class Solution {
/**
Go through #n element:
double-pointer for contrary sum of the i-th element: O(n)
Total: O(n^2)
**/
public List<List<Integer>> threeSum(int[] nums) {
int i = 0, n = nums.length, left = 0, right = n - 1, sum = 0;
if (n < 3)
{
return new LinkedList<>();
}
Arrays.sort(nums);
LinkedList<List<Integer>> ret = new LinkedList<>();
for (i=0; i<n-2; i++)
{
if (i > 0 && nums[i] == nums[i-1])
{
continue;
}
left = i + 1;
right = n - 1;
while (left < right)
{
sum = nums[left] + nums[right];
if (sum == -nums[i])
{
LinkedList<Integer> list = new LinkedList<Integer>();
list.add(nums[i]);
list.add(nums[left]);
list.add(nums[right]);
ret.add(list);
while (left < n-1 && nums[left] == nums[++left]);
}
else if (sum < -nums[i])
{
while (left < n-1 && nums[left] == nums[++left]);
}
else
{
while (right > 0 && nums[right] == nums[--right]);
}
}
}
return ret;
}
}