实测130毫秒,实在不想优化了,去重可以再考虑考虑,但是我懒。
import java.util.*;
class solution {
public static void main(String[] args) {
List<List<Integer>> arr = threeSum(new int[]{-4,-2,1,-5,-4,-4,4,-2,0,4,0,-2,3,1,-5,0});
}
static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> resultlist = new ArrayList<>();
Arrays.sort(nums);
int i, j, k;
for (i = 0; i < nums.length - 2; i++) {
j = i + 1;
k = nums.length - 1;
if(nums[i]>0){
break;
}else
if(i==0||nums[i]!=nums[i-1]){
while (j < nums.length && j < k) {//双指针前后同时寻找
if ((0 - nums[i]) == nums[j] + nums[k]) {
List<Integer> result = new ArrayList<Integer>();
result.add(nums[i]);
result.add(nums[j]);
result.add(nums[k]);
resultlist.add(result);
j++;
k--;
} else if ((0 - nums[i]) > nums[j] + nums[k]) {
j++;
} else {
k--;
}
}
}else{
continue;
}
}
/**
* 去重
*/
HashSet set = new HashSet(resultlist);
resultlist.clear();
resultlist.addAll(set);
return resultlist;
}
}
LeetCode15:三数之和
最新推荐文章于 2022-08-19 13:46:03 发布