Source: https://leetcode.com/problems/3sum/
Time: 2020/12/20
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.
Notice that the solution set must not contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Example 2:
Input: nums = []
Output: []
Example 3:
Input: nums = [0]
Output: []
Constraints:
0 <= nums.length <= 3000
-105 <= nums[i] <= 105
Solution
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
int i = 0;
if(nums.length < 3 || nums[nums.length - 1] < 0)
return res;
while(i < nums.length - 2)
{
if(nums[i] > 0)
break;
int target = 0 - nums[i];
int j = i + 1;
int k = nums.length - 1;
while(j < k)
{
if(nums[k] < 0)
break;
if(nums[j] + nums[k] == target)
{
res.add(Arrays.asList(nums[i],nums[j],nums[k]));
while(j < k && nums[j] == nums[++j]);
while(j < k && nums[k] == nums[--k]);
}
else if(nums[j] + nums[k] > target)
k--;
else
j++;
}
while(i < nums.length - 2 && nums[i] == nums[++i]);
}
return res;
}
}