[leetcode-18]4Sum(java)

问题描述:
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:
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)

分析:之前做了3sum的问题,这个问题就应该比较直接了,这里需要用O(n3)的方法。固定前两个,后两个由两端向中间逼近。
代码如下:616ms

public class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target){
        List<List<Integer>> res = new LinkedList<List<Integer>>();
        int first,second;
        int left,right;
        int numLen = nums.length;

        Arrays.sort(nums);
        for(first = 0;first<numLen;first++){
            while(first>0&&first<numLen&&nums[first]==nums[first-1])
                first++;
            for(second = first+1;second<numLen; second++){
                while(second>first+1&&second<numLen&&nums[second]==nums[second-1])
                    second++;
                if(second>=numLen)
                    break;

                left = second+1;
                right = numLen-1;
                int val1 = nums[first]+nums[second];
                while(left<right){
                    while(left>second+1&&left<numLen&&nums[left]==nums[left-1])
                        left++;
                    while(right>=0&&right+1<numLen&&nums[right]==nums[right+1])
                        right--;
                    if(right<0||left>=numLen)
                        break;

                    int val2 = val1+nums[left]+nums[right];

                    if(val2<target){
                        left++;
                    }else if(val2>target)
                        right--;
                    else{//val2 = target
                        List<Integer> tmpList = new LinkedList<Integer>();
                        tmpList.add(nums[first]);
                        tmpList.add(nums[second]);
                        tmpList.add(nums[left]);
                        tmpList.add(nums[right]);

                        res.add(tmpList);
                        left++;right--;
                    }
                }
            }
        }
        return res;
    }
}

网友提出了一种思路:4个元素,使用两两结合的方法,构成二元组。而二元组的和为key,构成一个key-value的链表。链表中的值为所有以此值为key的二元组。
起初我尝试了这种思路。发现至少存在如下几个问题:
1、如何判断一个四元组是有效的。比如,四元祖中是否有重复的元素。(可以用hashMap解决)
2、res表的去重问题。我发现不管之前怎么去重,但是最后都要进行一次查找去重。参考博客:这里写链接内容
他的代码里有两点很值得学习:

  1. 在将两个元素结合在一起的时候,他使用的是四元组,(两个元素,两个索引)。所以当两个元组合并时,只需要判断索引是否相同即可。索引相同,使用的是同一个元素。而我当初的想法是用一个hashtable,当两个元组合并起来时,查看新的四元组里面的元素个数,然后查看hashtable,看是否有足量的元素个数。相比之下,我的方法显得笨笨的。
  2. 在查找满足条件的四元组里,他使用的是遍历keyset,然后使用hashmap查找(target-key[i]),而我肯定是会从两端遍历keyset,这样又显得太笨了。

重写代码如下:700ms

public class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
       List<List<Integer>> res = new LinkedList<List<Integer>>();
        HashMap<Integer,LinkedList<int[]>> maps = new HashMap<Integer,LinkedList<int[]>>();

        Arrays.sort(nums);
        for(int i = 0;i<nums.length;i++){
            for(int j = i+1;j<nums.length;j++){
                int val = nums[i]+nums[j];

                int[] tetrad = new int[4];
                tetrad[0] = nums[i];tetrad[1] = i;tetrad[2] = nums[j];tetrad[3] = j;
                if(!maps.containsKey(val)){
                    LinkedList<int[]> tmpList = new LinkedList<int[]>();
                    maps.put(val,tmpList);
                }
                maps.get(val).add(tetrad);
            }
        }
        Integer[] newNums = maps.keySet().toArray(new Integer[maps.size()]);
        Arrays.sort(newNums);
        for(int i = 0;i<newNums.length;i++){
            int first = newNums[i];
            int second = target-newNums[i];
            if(maps.containsKey(second)){
                LinkedList<int[]> firstList = maps.get(first);
                LinkedList<int[]> secondList = maps.get(second);

                for(int firstIndex = 0;firstIndex<firstList.size();firstIndex++){
                    int[] firstTetrad = firstList.get(firstIndex);
                    for (int secondIndex = 0;secondIndex<secondList.size();secondIndex++){
                        int[] secondTetrad = secondList.get(secondIndex);


                        //查看是否有重复
                        if(firstTetrad[1]!=secondTetrad[1]&&firstTetrad[1]!=secondTetrad[3]
                                &&firstTetrad[3]!=secondTetrad[1]&&firstTetrad[3]!=secondTetrad[3]){
                           List<Integer> tmpList = Arrays.asList(firstTetrad[0],firstTetrad[2],
                                   secondTetrad[0],secondTetrad[2]);

                          Collections.sort(tmpList);
                            if(!res.contains(tmpList))
                                res.add(tmpList);
                        }
                    }
                }
            }
        }

        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值