zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 18 四数之和

    18. 四数之和

    给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。

    注意:

    答案中不可以包含重复的四元组。

    示例:

    给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。

    满足要求的四元组集合为:
    [
    [-1, 0, 0, 1],
    [-2, -1, 1, 2],
    [-2, 0, 0, 2]
    ]

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/4sum
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    class Solution {
         public List<List<Integer>> fourSum(int[] nums, int target) {
            int len = nums.length;
            List<List<Integer>> res = new ArrayList<List<Integer>>();        
            if(nums.length<4) return res;                  
            Arrays.sort(nums); 
            if(nums[0]>target/4 || nums[len-1]<target/4) return res;    
            for(int i = 0;i<len;i++){
                if(nums[i]>target/4) break;
                if(i>0 && nums[i]==nums[i-1]) continue;
                int sum = target-nums[i];
                for(int j = i+1;j<len;j++){
                    if(nums[j]>sum/3) break;
                    if(j>i+1 && nums[j]==nums[j-1]) continue;
                    int l = j+1;
                    int r = len-1;
                    while(l<r){
                        if(nums[r]<sum/3) break;
                        int temp = nums[j] + nums[l] +nums[r];
                        if(temp == sum){
                            res.add(Arrays.asList(nums[i],nums[j],nums[l],nums[r]));
                            while(l<r && nums[l] == nums[l+1]) l++;
                            while(l<r && nums[r] == nums[r-1]) r--;
                            l++;
                            r--;
                        }else if(temp>sum){//结果大了右指针往左
                            r--;
                        }else{//结果小了左指针往右
                            l++;
                        }
                    }
                }
            }
            return res;
        }
    }
    
  • 相关阅读:
    boost test学习(二)
    log4cxx的使用(2)
    Windows CE下流驱动的动态加载
    linux powerqorpp1010rdb 编译过程
    cadence allegro 设计重用
    Linux中VMware虚拟机硬盘空间扩大方法
    WINCE系统启动直接运行自己的程序
    linux6410触摸屏驱动
    cadence allegro和ad9之间的转换
    wince 6.0和5.0的区别
  • 原文地址:https://www.cnblogs.com/a1439775520/p/12946915.html
Copyright © 2011-2022 走看看