zoukankan      html  css  js  c++  java
  • LeetCode#18-四数之和

    package shuangzhizhen;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    /*
    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]
    ]
     */
    public class p18 {
        public List<List<Integer>> fourSum(int[] nums, int target) {
            List<List<Integer>> list = new ArrayList<List<Integer>>();
            if (nums.length < 4) return list;
            Arrays.sort(nums);
            for (int i = 0; i < nums.length-3; i++) {
                if (i > 0 && nums[i] == nums[i-1]) continue;//去重
    
                for (int j =i+1; j<nums.length-2; j++) {
                    if (j >i+1 && nums[j] == nums[j-1]) continue;
                    int minValue=nums[i]+nums[j]+nums[j+1]+nums[j+2];
                    int maxValue=nums[i]+nums[j]+nums[nums.length-2]+nums[nums.length-1];
                    if(minValue>target||maxValue<target)continue;
    
                    int l = j + 1, r = nums.length-1;//双指针
                    while (l<r) {
                        //if(nums[l]==nums[l-1])l++;
                        //if(nums[r]==nums[r-1])r--;
                        int tmp = nums[i]+nums[j]+nums[l]+nums[r];
                        if (tmp == target) {//插入表
                            list.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 (tmp<target) {//小了
                            l++;
    
                        } else r--;//大了
                    }
                }
            }
            return list;
    
        }
    
    }
    

      运行结果:

  • 相关阅读:
    WebSocket简单使用
    viewport 的基本原理以及使用
    Markdown基本语法总结
    emmet 工具的基本使用,总结
    在idea中把项目上传到GitHub库中
    Git Bash命令汇总
    用github创建自己的存储库并把文件推送到远程库中
    之前编写的Symfony教程已经可以观看了
    Symfony路由配置教程已开课
    Symfony原创视频教程
  • 原文地址:https://www.cnblogs.com/jifeng0902/p/13289211.html
Copyright © 2011-2022 走看看