栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

leetcode-18. 四数之和

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

leetcode-18. 四数之和

不解释了,直接上代码,代码详细注释。

class Solution {
    public List> fourSum(int[] nums, int target) {
    //使用双指针法,首先排序
        Arrays.sort(nums);
        List> res = new LinkedList<>();
        for(int i = 0; i < nums.length; ++i){
           
            List> tmp = threeSum(nums, i + 1, target - nums[i]);
            for(List tuple : tmp){
                tuple.add(nums[i]);
                res.add(tuple);
            }
            //下面这个while为什么不能放到前面呢?
            //因为先找第一个数是target的三元组,如果先把指针移动到最后一个相同元素去寻找,
            //那么结果中将缺少,含有相同元素,但是正确答案的三元组。
            while(i < nums.length - 1 && nums[i] == nums[i + 1]) i++;
        }
        return res;
    }
    //3sum问题
      public List> threeSum(int[] nums, int start, int target) {
        
        List> res = new LinkedList<>();
        for(int i = start; i < nums.length; ++i){
           
            List> tmp = twoSum(nums, i + 1, target - nums[i]);
            for(List tuple : tmp){
                tuple.add(nums[i]);
                res.add(tuple);
            }
            //下面这个while为什么不能放到前面呢?
            //因为先找第一个数是target的三元组,如果先把指针移动到最后一个相同元素去寻找,
            //那么结果中将缺少,含有相同元素,但是正确答案的三元组。
            while(i < nums.length - 1 && nums[i] == nums[i + 1]) i++;
        }
        return res;
    }
    //twoSum问题
    public List> twoSum(int[] nums, int start,int  target){
        int lo = start;
        int rh = nums.length - 1;
        List> res = new LinkedList<>();     
        while(lo < rh){
            int left = nums[lo];
            int right = nums[rh];
            int sum = nums[lo] + nums[rh];
            if(sum < target){
                //这里所有的while都是为了去重。
                //例如:1, 2, 2,3    使用了2后,要移动到3.
                while(lo < rh && nums[lo] == left) lo ++;
            }else if(sum > target){
                while(lo < rh && nums[rh] == right) rh --;
            }else{
                List tmp = new LinkedList<>();
                tmp.add(left);
                tmp.add(right);
                res.add(tmp);
                while(lo < rh && nums[lo] == left) lo ++;
                while(lo < rh && nums[rh] == right) rh --;
            }
        }
        return res;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/893389.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号