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.
1
2
3
4
5
6
7
8
9
| Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
|
Solution:
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
| class Solution {
public List<List<Integer>> threeSum(int[] nums) {
if (nums.length < 3) {
return Collections.emptyList();
}
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
Set<String> uniq = new HashSet<>();
Map<Integer, Integer> valueToIndex = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
valueToIndex.put(nums[i], i);
}
int i = 0;
while (i < nums.length - 1) {
for (int j = i + 1; j < nums.length; j++) {
Integer sum = -(nums[i] + nums[j]);
Integer sumIndex = valueToIndex.get(sum);
if (sumIndex != null
&& sumIndex != i
&& sumIndex != j
&& sumIndex > j
&& uniq.contains("" + nums[i] + nums[j] + sumIndex) == false) {
result.add(List.of(nums[i], nums[j], sum));
uniq.add("" + nums[i] + nums[j] + sumIndex);
}
}
i++;
}
return result;
}
}
|
Solution Without Space#
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
| class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int n = nums.length;
if (n < 3) return Collections.emptyList();
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (i > 0 && nums[i] == nums[i - 1]) { // add only first occurence
continue;
}
int lo = i + 1;
int hi = n - 1;
int sum = - nums[i];
while (lo < hi) {
if (nums[lo] + nums[hi] == sum) {
res.add(List.of(nums[i], nums[lo], nums[hi]));
while (lo < hi && nums[lo] == nums[lo + 1]) lo++; // skip duplicates
while (lo < hi && nums[hi] == nums[hi - 1]) hi--;
lo++;
hi--;
} else if (nums[lo] + nums[hi] < sum) {
lo++;
} else {
hi--;
}
}
}
return res;
}
}
|
Solution 2021-11-23#
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
| class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int n = nums.length;
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (i > 0 && nums[i] == nums[i-1]) continue;
int lo = i + 1;
int hi = n - 1;
int target = -nums[i];
while (lo < hi) {
if (nums[lo] + nums[hi] > target) {
hi--;
} else if (nums[lo] + nums[hi] < target) {
lo++;
} else {
res.add(List.of(nums[i], nums[lo], nums[hi]));
while (lo < hi && nums[lo] == nums[lo + 1]) lo++;
while (lo < hi && nums[hi - 1] == nums[hi]) hi--;
lo++;
hi--;
}
}
}
return res;
}
}
|