该题可以先将数字排序,然后用双指针算法来解题。本文没有使用双指针,而是利用HashMap来解题。
public class LC15_threeSum {
public List<List<Integer>> threeSum(int[] nums) {
HashMap<Integer, Integer> hashMap = new HashMap<>();
HashSet<List<Integer>> hashSet= new HashSet<>();
List<List<Integer>> lists = new ArrayList<>();
for (int i = 0; i < nums.length; i++){
hashMap.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++)
for (int j = i + 1; j < nums.length; j++){
int ans = -1;
if (hashMap.get(-(nums[i]+nums[j])) != null){
ans = hashMap.get(-(nums[i]+nums[j]));
}
if (ans > j && ans != -1){
List<Integer> list = new ArrayList<>();
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[ans]);
Collections.sort(list);
hashSet.add(list);
}
}
for (List<Integer> list : hashSet) {
lists.add(list);
}
return lists;
}
}