18. 四數之和

題目:

給定一個包含 n 個整數的數組 nums 和一個目標值 target,判斷 nums 中是否存在四個元素 a,b,c 和 d ,使得 a + b + c + d 的值與 target 相等?找出所有滿足條件且不重複的四元組。

注意:

答案中不可以包含重複的四元組。

示例:

給定數組 nums = [1, 0, -1, 0, -2, 2],和 target = 0。

滿足要求的四元組集合爲:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

思路:

和三數之和一樣,只是多個for循環

代碼:

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        if(nums==null)
            return null;
        Arrays.sort(nums);
        List<List<Integer>> ans=new ArrayList<List<Integer>>();
        for(int i=0;i<nums.length-2;i++){
            for(int l=nums.length-1;l>i+2;l--){
                if(i>=1&&nums[i]==nums[i-1]) {//去重1,i是從前往後,所以與i-1比較。
                    break;
                }
                if(l<=nums.length-2&&nums[l]==nums[l+1])//去重1,i是從前往後,所以與i-1比較。
                    continue;
                int j=i+1,k=l-1;
                while(j<k){
                    if(nums[i]+nums[j]+nums[k]+nums[l]==target){
                        ans.add(Arrays.asList(nums[i],nums[j],nums[k],nums[l]));
                        j++;k--;
                        while(j<k&&nums[j]==nums[j-1])j++;//去重2,j是從前往後,所以與j-1比較
                        while(j<k&&nums[k]==nums[k+1])k--;//去重3,k是從後往前,與k+1比較。
                    }else if(nums[i]+nums[j]+nums[k]+nums[l]>target)
                        k--;
                    else
                        j++;
                }
            }

        }
        return ans;

    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章