18. 4Sum

作者: wtmxx | 来源:发表于2018-02-08 09:42 被阅读0次

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

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> zz = new ArrayList<>();
        Arrays.sort(nums);
        int len = nums.length;
        if(len<4)
            return zz;
        for(int i=0;i<len-3;i++){
            while(i!=0&&i<len-3&&nums[i]==nums[i-1])i++;
            for(int j=i+1;j<len-2;j++){
                while(j!=i+1&&j<len-2&&nums[j]==nums[j-1])j++;
                int p = j+1,q = len-1;
                while(p<q){
                    int dis = nums[i]+nums[j]+nums[p]+nums[q]-target;
                    if(dis<0){
                        p++;
                    }else if(dis==0){
                        List<Integer> tmp = new ArrayList<>();
                        tmp.add(nums[i]);
                        tmp.add(nums[j]);
                        tmp.add(nums[p]);
                        tmp.add(nums[q]);
                        zz.add(tmp);
                        p++;
                        q--;
                        while(p<q&&nums[p]==nums[p-1])p++;
                        while(p<q&&nums[q]==nums[q+1])q--;
                    }else{
                        q--;
                    }
                }
            }
        }
        return zz;
    }
}

相关文章

  • 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/ldwzzxtx.html