18. 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 class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        HashSet<ArrayList<Integer>> hashset = new HashSet<ArrayList<Integer>>();
        List<List<Integer>> rec = new LinkedList<>();//这里还不知道为什么可以这样
        if(nums.length<4||nums==null)
          return rec;
        Arrays.sort(nums);
        
        for(int i=0;i<nums.length-3;i++)
          for(int j=i+1;j<nums.length-2;j++)
            {
                int k = j+1;
                int l = nums.length-1;
                while(k<l)
                 {
                     int sum = nums[i]+nums[j]+nums[k]+nums[l];
                     if(sum>target)
                        l--;
                     else if(sum<target)
                        k++;
                     else
                        {
                            ArrayList<Integer> result = new ArrayList<Integer>();
                            result.add(nums[i]);
                            result.add(nums[j]);
                            result.add(nums[k]);
                            result.add(nums[l]);
                            if(!hashset.contains(result))
                                hashset.add(result);
                            k++;
                            l--;
                        }
                 }
            }
            
        
        rec.addAll(hashset);
        return rec;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,951评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 11,383评论 0 23
  • 今天在中医育儿群里,听到有位妈妈说孩子被狗吓到了,晚上哭闹,有人建议多抱抱,多安抚,按摩肾经。 突然想起之前聚友礼...
    若水柳柳柳阅读 384评论 0 1
  • 基督教的朋友每天会发一句话,其中一句~喜乐的心,乃是良药!忧伤的灵,使人骨枯! 这句话,原来没有感觉,现在感觉越来...
    热爱生活的广佳阅读 345评论 1 0
  • 光通量、光强、照度、亮度的联系 光强指的是光通量在每弧度上的单位值。照度指的是光通量在每平方米上的单位值。亮度指的...
    wendy_要努力努力再努力阅读 439评论 0 0

友情链接更多精彩内容