18. 4Sum

作者: liuhaohaohao | 来源:发表于2018-06-26 20:10 被阅读0次

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

The solution set must not contain duplicate quadruplets.

Example:

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

Solution

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {    
        Arrays.sort(nums); 
        List<List<Integer>> result = new ArrayList<>();
        
        for (int l = 0; l < nums.length - 3; l++){
            if (l > 0 && nums[l] == nums[l-1]){                         //避免重复答案
                continue;
            }
            for (int i = l + 1; i < nums.length - 2; i++){
                if (i > l + 1 && nums[i] == nums[i-1]){                 //避免重复答案
                    continue;
                }
                int j = i + 1;
                int k = nums.length - 1;
                while (j < k){
                    int sum = nums[l] + nums[i] + nums[j] + nums[k];
                    if (sum == target){
                        result.add(Arrays.asList(nums[l], nums[i], nums[j], nums[k]));
                        j++;
                        k--;
                        while (j < k && nums[j] == nums[j-1])   j++;    //避免重复答案
                        while (j < k && nums[k] == nums[k+1])   k--;    //避免重复答案
                    }else if (sum > target){                            //如果求和偏大,则右指针左移一位
                        k--;
                    }else if (sum < target){                            //如果求和偏小,则左指针右移一位
                        j++;
                    }

                }
            }
        }
        
        return result;
    }
}

相关文章

  • LeetCode #18 2018-07-28

    18. 4Sum Given an array nums of n integers and an integer...

  • 力扣每日一题:18.四数之和

    18.四数之和 https://leetcode-cn.com/problems/4sum/[https://le...

  • 18.四数之和

    18.四数之和 题目链接:https://leetcode-cn.com/problems/4sum/[https...

  • leetcode 18. 4Sum

    leetcode 18. 4Sum 题目,但是其解题思路可以延伸到 ksum 参考:1 ksum

  • 18. 4Sum

    Given an array nums of n integers and an integer target, ...

  • 18. 4Sum

    Given an array nums of n integers and an integer target, ...

  • 18. 4Sum

    Description Given an array S of n integers, are there ele...

  • 18. 4Sum

    在3Sum基础上,固定第一个数对剩下的数进行3Sum计算,复杂度为O(n^3)

  • 18. 4Sum

    题目描述:给定一个有n个整数的数组S和目标值target,找到其中所有由四个数a、b、c、d组成,使得a + b ...

  • 18. 4Sum

    题目 Given an array S of n integers, are there elements a, ...

网友评论

      本文标题:18. 4Sum

      本文链接:https://www.haomeiwen.com/subject/lhamyftx.html