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] ]
使用HashMap优化
My solution :
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<>();
List<List<Integer>> ans = new ArrayList<List<Integer>>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++ ) {
int complement = - (nums[i] + nums[j]);
if (map.containsKey(complement)) {
int complementIndex = map.get(complement);
if ( complementIndex != i && complementIndex != j) {
List<Integer> res = new ArrayList<>();
res.add(nums[i]);
res.add(nums[j]);
res.add(complement);
Collections.sort(res);
boolean isExit = false;
for (int x = 0; x < ans.size(); x++) {
boolean same = true;
for (int y = 0; y < ans.get(x).size(); y ++) {
if (ans.get(x).get(y) != res.get(y)) {
same = false;
break;
}
}
if (same) {
isExit = true;
break;
}
}
if(!isExit)
ans.add(res);
}
}
}
}
return ans;
}
}