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;
        }
    }
    
  • 相关阅读:
    UVa 12174 (滑动窗口) Shuffle
    UVa 1607 (二分) Gates
    CodeForces ZeptoLab Code Rush 2015
    HDU 1525 (博弈) Euclid's Game
    HDU 2147 (博弈) kiki's game
    UVa 11093 Just Finish it up
    UVa 10954 (Huffman 优先队列) Add All
    CodeForces Round #298 Div.2
    UVa 12627 (递归 计数 找规律) Erratic Expansion
    UVa 714 (二分) Copying Books
  • 原文地址:https://www.cnblogs.com/a1439775520/p/12946915.html
Copyright © 2011-2022 走看看