15. 3Sum (Medium)
https://leetcode.com/problems/3sum/
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] ]
Solutions
class Solution {
// Adopt a series of optimization operations to reduce the time cost.
public List<List<Integer>> threeSum(int[] nums) {
int len = nums.length;
List<List<Integer>> ans = new ArrayList<>();
if (len < 3) {
return ans;
}
Arrays.sort(nums);
for (int i = 0; i < len - 2; i++) {
// nums[i - 1] is already calculated, skip nums[i] if same value with previous one
if (i != 0 && nums[i] == nums[i - 1]) {
continue; // optimization 1
}
// Scan from i + 1 because i, j plays same role which you can be understood
// that (i,j) is equivalent with (j,i)
int j = i + 1;
int k = len - 1;
while (k > j) {
if (j != i + 1 && nums[j] == nums[j - 1]) { // optimization 2, same as 1
j++;
continue;
}
if (k != len - 1 && nums[k] == nums[k + 1]) { // optimization 3, same as 1
k--;
continue;
}
int sum = nums[i] + nums[j] + nums[k];
if (sum > 0) {
k--;
}
if (sum < 0) {
j++;
}
if (sum == 0) {
ans.add(Arrays.asList(nums[i], nums[j], nums[k]));
k--;
j++;
}
}
}
return ans;
}
}
Incorrect Solutions
class Solution {
// This solution takes up too much resources.
// Time Limit Exceeded
public List<List<Integer>> threeSum(int[] nums) {
int len = nums.length;
List<List<Integer>> ans = new ArrayList<>();
if (len < 3) {
return ans;
}
Arrays.sort(nums);
// keep count of the elements
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (!map.containsKey(nums[i])) {
map.put(nums[i], 0);
}
map.put(nums[i], map.get(nums[i]) + 1);
}
// Used to keep the temporary answers which allow duplicates
List<List<Integer>> tmpAns = new ArrayList<>();
for (int i = 0; i < len; i++) {
map.put(nums[i], map.get(nums[i]) - 1);
for (int j = i + 1; j < len; j++) {
int k = -(nums[i] + nums[j]);
if (!map.containsKey(k)) {
continue;
}
map.put(nums[j], map.get(nums[j]) - 1);
if (map.get(k) > 0) {
List<Integer> triplet = Arrays.asList(new Integer[]{nums[i], nums[j], k});
triplet.sort(Comparator.comparingInt(o -> o));
tmpAns.add(triplet);
}
map.put(nums[j], map.get(nums[j]) + 1);
}
map.put(nums[i], map.get(nums[i]) + 1);
}
// Remove duplicates from the answers.
List<String> hashes = new ArrayList<>();
for (int i = 0; i < tmpAns.size(); i++) {
String hash = tmpAns.get(i).toString();
if (hashes.contains(hash)) {
continue;
}
hashes.add(hash);
ans.add(tmpAns.get(i));
}
return ans;
}
}