Leetcode 15. 3Sum (Medium) (java)
Tag: Array, Two Pointers
Difficulty: Medium
/*
15. 3Sum (Medium)
Given an array S of n integers, are there elements a, b, c in S 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.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
*/
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
int _size = nums.length;
if (_size < 3) {
return res;
}
Arrays.sort(nums);
for (int i = 0; i < _size - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1] || nums[i] + nums[_size - 1] + nums[_size - 2] < 0) {
continue;
}
if (nums[i] + nums[i + 1] + nums[i + 2] > 0) {
break;
}
int j = i + 1, k = _size - 1;
while (j < k) {
int _sum = nums[i] + nums[j] + nums[k];
if (_sum == 0) {
res.add(Arrays.asList(nums[i], nums[j++], nums[k--]));
while (j < k && nums[k] == nums[k + 1]) {
k--;
}
while (j < k && nums[j] == nums[j - 1]) {
j++;
}
} else if (_sum > 0) {
k--;
}
else {
j++;
}
}
}
return res;
}
}