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;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問(wèn)題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,890評(píng)論 0 33
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,016評(píng)論 0 23
  • 今天在中醫(yī)育兒群里,聽(tīng)到有位媽媽說(shuō)孩子被狗嚇到了,晚上哭鬧,有人建議多抱抱,多安撫,按摩腎經(jīng)。 突然想起之前聚友禮...
    若水柳柳柳閱讀 374評(píng)論 0 1
  • 基督教的朋友每天會(huì)發(fā)一句話(huà),其中一句~喜樂(lè)的心,乃是良藥!憂(yōu)傷的靈,使人骨枯! 這句話(huà),原來(lái)沒(méi)有感覺(jué),現(xiàn)在感覺(jué)越來(lái)...
    熱愛(ài)生活的廣佳閱讀 333評(píng)論 1 0
  • 光通量、光強(qiáng)、照度、亮度的聯(lián)系 光強(qiáng)指的是光通量在每弧度上的單位值。照度指的是光通量在每平方米上的單位值。亮度指的...
    wendy_要努力努力再努力閱讀 425評(píng)論 0 0

友情鏈接更多精彩內(nèi)容