18. 4Sum

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums 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.

Example:

Given array nums = [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]
]

Solution

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {    
        Arrays.sort(nums); 
        List<List<Integer>> result = new ArrayList<>();
        
        for (int l = 0; l < nums.length - 3; l++){
            if (l > 0 && nums[l] == nums[l-1]){                         //避免重復(fù)答案
                continue;
            }
            for (int i = l + 1; i < nums.length - 2; i++){
                if (i > l + 1 && nums[i] == nums[i-1]){                 //避免重復(fù)答案
                    continue;
                }
                int j = i + 1;
                int k = nums.length - 1;
                while (j < k){
                    int sum = nums[l] + nums[i] + nums[j] + nums[k];
                    if (sum == target){
                        result.add(Arrays.asList(nums[l], nums[i], nums[j], nums[k]));
                        j++;
                        k--;
                        while (j < k && nums[j] == nums[j-1])   j++;    //避免重復(fù)答案
                        while (j < k && nums[k] == nums[k+1])   k--;    //避免重復(fù)答案
                    }else if (sum > target){                            //如果求和偏大,則右指針左移一位
                        k--;
                    }else if (sum < target){                            //如果求和偏小,則左指針右移一位
                        j++;
                    }

                }
            }
        }
        
        return result;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容