zoukankan      html  css  js  c++  java
  • 18. 4Sum

    题目链接:https://leetcode.com/problems/4sum/

    解题思路:

    和3sum一样,不过固定前两个数而已。

    class Solution {
        public List<List<Integer>> fourSum(int[] nums, int target) {
            List<List<Integer>> res = new ArrayList<>();
            if(nums.length<4 || nums==null)
                return res;
            HashSet<ArrayList<Integer>> hs = new HashSet<>();
            
            Arrays.sort(nums);
            
            for(int i=0;i<=nums.length-4;i++)
            {
                
                for(int j=i+1;j<=nums.length-3;j++)
                {
                    int low = j+1;
                    int high = nums.length-1;
                    
                    while(low < high)
                    {
                        int sum = nums[i]+nums[j]+nums[low]+nums[high];
                        
                        if(sum==target)
                        {
                            ArrayList<Integer> un = new ArrayList<Integer>();
                            un.add(nums[i]);
                            un.add(nums[j]);
                            un.add(nums[low]);
                            un.add(nums[high]);
                            
                            if(!hs.contains(un))
                            {
                                res.add(un);
                                hs.add(un);
                            }
                            low++;
                            high--;
                        }
                        
                        else if(sum>target)
                        {
                            high--;
                        }
                        else if(sum<target)
                        {
                            low++;
                        }
                    }
                }
                
               
            }
            return res;
        }
    }
  • 相关阅读:
    C#对象初始化器
    C#构造方法
    C#方法重载
    C#方法
    C#类 对象 字段和属性
    C#数组
    C#字符串
    C#原码反码补码
    字段、方法、属性
    单例模式、异常
  • 原文地址:https://www.cnblogs.com/wangyufeiaichiyu/p/10828215.html
Copyright © 2011-2022 走看看