本题用排序+双指针比较容易理解解决,先进行排序,然后for遍历数组,在遍历过程中使用左右指针对一些细节判断。下面的答案提交后效率不高,可能是用来HashSet的原因,时间复杂度更高了。
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
Set<List<Integer>> set = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0) {
return res;
}
int l = i + 1;
int h = nums.length - 1;
int sum = 0;
while (l < h) {
sum = nums[i] + nums[l] + nums[h];
if (sum < 0) {
l++;
}
if (sum > 0) {
h--;
}
if (sum == 0) {
List<Integer> list = new ArrayList<>();
list.add(nums[i]);
list.add(nums[l]);
list.add(nums[h]);
if (!set.contains(list)) {
res.add(list);
set.add(list);
}
h--;
}
}
}
return res;
}
}