LeetCode:4Sum

4Sum




Total Accepted: 75786  Total Submissions: 314216  Difficulty: Medium

Given an array S of n integers, are there elements abc, 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]
]

Subscribe to see which companies asked this question

Hide Tags
  Array Hash Table Two Pointers
Hide Similar Problems
  (E) Two Sum (M) 3Sum
























思路:

承接【3Sum】,由加一个指针即可。

java code:

public class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        int n = nums.length;
        Arrays.sort(nums);
        for(int i=0;i<n-3;i++) {
            
            if(i > 0 && nums[i]==nums[i-1]) continue;
            for(int j=i+1;j<n-2;j++) {
                if(j>i+1 && nums[j]==nums[j-1]) continue;
                int left = j + 1, right = n - 1;
                while(left < right) {
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    
                    if(sum == target) {
                        ans.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
                        while(left < right && nums[left]==nums[left+1]) left++;
                        while(left < right && nums[right]==nums[right-1]) right--;
                    }
                    if(sum < target)
                        left++;
                    else // sum >= target
                        right--;
                }
            }
        }
        return ans;
    }
}


你可能感兴趣的:(LeetCode,array,table,hash,Two,Pointers)