一、今日刷题
1. 第六部分:哈希表 – 15. 三数之和
答案代码:
package HashSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author: LYZ
* @date: 2022/2/15 15:53
* @description: 15.三数之和
*/
public class ThreeSum {
public static void main(String[] args) {
ThreeSum threeSum = new ThreeSum();
int[] nums = {-1,0,1,2,-1,-4};
List<List<Integer>> ans = threeSum.threeSum(nums);
System.out.println(ans);
}
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
if (nums == null || nums.length < 3) {
return ans;
}
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
if (nums[i] > 0) {
break;
}
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int left = i + 1;
int right = nums.length - 1;
int target = -nums[i];
while (left < right) {
if (nums[left] + nums[right] == target) {
List<Integer> list = new ArrayList<>();
list.add(nums[i]);
list.add(nums[left]);
list.add(nums[right]);
ans.add(list);
left++;
right--;
while (nums[left] == nums[left - 1] && left < right) {
left++;
}
while (nums[right] == nums[right + 1] && left < right) {
right--;
}
} else if (nums[left] + nums[right] < target) {
left++;
} else {
right--;
}
}
}
return ans;
}
}
学习题解中一个评论的思路