-
-
- import java.util.*;
-
- /**
- * @author xienl
- * @description 三数之和
- * @date 2022/6/30
- */
-
- public class Solution {
- public static void main(String[] args) {
- Solution solution = new Solution();
- int[] num = {0 , 0, 0 , 0};
- System.out.println(solution.threeSum(num));
- }
-
- /**
- * 三层循环,不行,复杂度过大,执行不完
- * @param num
- * @return
- */
- public ArrayList<ArrayList<Integer>> threeSum2(int[] num) {
- Arrays.sort(num);
- Set<ArrayList<Integer>> res = new HashSet<>();
- for (int i = 0; i < num.length; i++){
- for (int j = i + 1; j < num.length; j++){
- for (int k = j + 1; k < num.length; k++){
- if (num[i] + num[j] + num[k] == 0) {
- ArrayList<Integer> temp = new ArrayList<>();
- temp.add(num[i]);
- temp.add(num[j]);
- temp.add(num[k]);
- Collections.sort(temp);
- res.add(temp);
- }
- }
- }
- }
- return new ArrayList<>(res);
- }
-
- /**
- * 双指针
- * 如果第一个值为a 要想结果为0 ,必须要 第二个和第三个值相加为-a
- * @param num
- * @return
- */
- public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
- if (num.length < 3){
- return new ArrayList<>();
- }
- Arrays.sort(num);
- ArrayList<ArrayList<Integer>> res = new ArrayList<>();
- int n = num.length;
- for (int i = 0; i < n - 2; i++){
- if (i != 0 && num[i] == num[i - 1]) {
- continue;
- }
- if (num[i] > 0){
- break;
- }
- int target = -num[i];
- int left = i + 1;
- int right = n - 1;
- while (left < right){
- // 两数字和
- int sum = num[left] + num[right];
- if (sum == target){
- ArrayList<Integer> temp = new ArrayList<>();
- temp.add(num[i]);
- temp.add(num[left]);
- temp.add(num[right]);
- res.add(temp);
-
- // 去重
- while (left + 1 < right && num[left] == num[left + 1]){
- left++;
- }
- while (right - 1 > left && num[right] == num[right - 1]){
- right--;
- }
- left++;
- right--;
- } else if (sum > target){
- right--;
- } else {
- left++;
- }
- }
- }
- return res;
- }
- }