18. 4Sum

一、题目

  1、审题

    

  2、分析:

    求所给数组中选取4个数字之和等于 target 的所有组合。

 

二、解答

  1、分析:

    a、数组进行排序,依次遍历数组下标为 i 的元素 ;

    b、遍历元素时,target - nums[i]  即为 剩余的数组中的元素求三数之和。

  

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {

        List<List<Integer>> resultList = new ArrayList<List<Integer>>();
        int len = nums.length;
        if(len < 4)
            return resultList;

        Arrays.sort(nums);
        for (int i = 0; i < len - 3; i++) {
            int threeSum = target - nums[i];

            if(i == 0 || nums[i] != nums[i-1])  // 
                
            for (int j = i+1; j < len - 2; j++) {
                int low = j + 1, high = len - 1;


                while (low < high) {
                    int sum = nums[j] + nums[low] + nums[high];
                    if (sum == threeSum) {
                        resultList.add(Arrays.asList(nums[i], nums[j], nums[low], nums[high]));

                        while (low < high && nums[low] == nums[low + 1]) low++;
                        while (low < high && nums[high] == nums[high - 1]) high--;

                        low++;
                        high--;
                    } else if (sum > threeSum)
                        high--;
                    else
                        low++;
                }
            }
        }
        // 去重
        List<List<Integer>> list = new ArrayList<List<Integer>>(new HashSet(resultList));
        return list;
    }
}

 

posted @ 2018-08-02 23:50  skillking2  阅读(102)  评论(0编辑  收藏  举报