zoukankan      html  css  js  c++  java
  • 4Sum

    Given an array S of n integers, are there elements a, b, c, 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: 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 List<List<Integer>> fourSum(int[] nums, int target) {
            int length = nums.length;
            Arrays.sort(nums);
            List<List<Integer>> lists = new ArrayList<>();
            for (int i = 0; i < length-3; i++) {
                if (i>0&&nums[i] == nums[i-1]){
                    continue;
                }
                for (int j=i+1; j < length-2;j++){
                    if (j>i+1&&nums[j]==nums[j-1]){
                        continue;
                    }
                    int head = j+1;
                    int tail = length-1;
    
                    while (head<tail){
                        int tmp = nums[i]+nums[j]+nums[head]+nums[tail];
                        if (tmp<target){
                            head++;
                        }
                        else if (tmp>target){
                            tail--;
                        }
                        else {
                            lists.add(Arrays.asList(nums[i],nums[j],nums[head],nums[tail]));
    
                            int k = head+1;
                            while (k<tail&&nums[k]==nums[k-1]){
                                k++;
                            }
                            head = k;
    
                            int l = tail-1;
                            while (l>head&&nums[l]==nums[l+1]){
                                l--;
                            }
                            tail = l;
                        }
                    }
                }
            }
            return lists;
        }
    
  • 相关阅读:
    EJB
    Token
    FreeMarker
    solr
    maven学习四:maven集成jetty插件发布web项目 标签: maven
    代码生成器
    springIOplatform
    数据连接池
    freeMark模板引擎
    张萌作品集
  • 原文地址:https://www.cnblogs.com/bingo2-here/p/7873567.html
Copyright © 2011-2022 走看看