package com.zmz.algorithm.hashtable;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 张明泽
 * Create by 2022/5/31 16:05
 * 四数之和
 * LeetCode-18
 */
public class FourTogether {
    public static void main(String[] args) {
        int[] nums = {-3,-1,0,2,4,5};
        List<List<Integer>> result = fourSum(nums,2);
        System.out.println(result);
    }

    /**
     * 根据三数之和去改思路
     * 两个for循环 两个指针
     * 在定义左右的移动指针
     */
    public static List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> lists = new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i-1]) continue;
            for (int j = i + 1; j < nums.length; j++) {
                if (j > i + 1 && nums[j] == nums[j-1]) continue;
                int left = j + 1;
                int right = nums.length - 1;
                while (left < right) {
                    if (nums[i] + nums[j] + nums[left] + nums[right] == target) {
                        ArrayList list = new ArrayList();
                        list.add(nums[i]);
                        list.add(nums[j]);
                        list.add(nums[left]);
                        list.add(nums[right]);
                        lists.add(list);
                        while (left < right && nums[left] == nums[left + 1]) left++;
                        while (left < right && nums[right] == nums[right - 1]) right--;
                        left++;
                        right--;
                    }
                    else if (nums[i] + nums[j] + nums[left] + nums[right] < target) {
                        left++;
                    } else {
                        right--;
                    }
                }
            }

        }
        return lists;
    }
}
最后修改:2022 年 06 月 02 日 10 : 04 AM
赏杯咖啡喝 谢谢您~