zoukankan      html  css  js  c++  java
  • [leedcode 18] 4Sum

    Given an array S of n integers, are there elements abc, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

    Note:

    • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
    • The solution set must not contain duplicate quadruplets.
        For example, given array S = {1 0 -1 0 -2 2}, and target = 0.
    
        A solution set is:
        (-1,  0, 0, 1)
        (-2, -1, 1, 2)
        (-2,  0, 0, 2)

    public class Solution {
        public List<List<Integer>> fourSum(int[] nums, int target) {
            //时间复杂度O(n^3)
            //注意去重
            Arrays.sort(nums);
            List<List<Integer>> res=new ArrayList<List<Integer>>();
            for(int i=0;i<nums.length;i++){
                if(i>0&&nums[i]==nums[i-1])continue;//去重
                for(int j=i+1;j<nums.length;j++){
                    if(j>i+1&&nums[j]==nums[j-1])continue;//去重
                    int left=j+1;
                    int right=nums.length-1;
                    int temp=target-nums[i]-nums[j];
                    while(left<right){
                        if(temp==nums[left]+nums[right]){
                            List<Integer> seq=new ArrayList<Integer>();
                            seq.add(nums[i]);
                            seq.add(nums[j]);
                            seq.add(nums[left++]);
                            seq.add(nums[right--]);
                            res.add(seq);
                            while(left<right&&nums[left-1]==nums[left])left++;//去重
                        }else{
                            if(temp>nums[left]+nums[right]){
                                left++;
                            }else right--;
                                                    
                        }                                        
                        
                    }
                    
                }
            }
                            return res;
        }
    }
  • 相关阅读:
    并发解决方案
    主外键
    ms
    mq消息丢失
    五种IO模型
    程序运行时间计算gettimeofday&clock_gettime
    exec与xargs区别
    mysql修改数据存放路径(linux)
    od用不同的编码输出文件内容
    segfault at f0 ip 00007f9954108feb sp 00007fffb5e64fc0 error 4 in libxxx.so[7f99540df000+54000]
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4627081.html
Copyright © 2011-2022 走看看