Skip to content

Latest commit

 

History

History
52 lines (48 loc) · 1.48 KB

18_4sum.md

File metadata and controls

52 lines (48 loc) · 1.48 KB

18 - 4Sum

leetcode link

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]
]

2 pointers solution - O(n^3)

// 12/09/2020
// two pointers approach - same as 3sum - O(n^3)
vector<vector<int>> fourSum(vector<int>& nums, int target) {
    if(nums.size() < 4) return {};
    sort(nums.begin(), nums.end());
    vector<vector<int>> result;
    for(int i = 0, size = nums.size(); i < size-3; ++i){
        if(i>0 && nums[i] == nums[i-1]) continue;
        for(int j = i+1; j < size-2; ++j){
            if(j>i+1 && nums[j] == nums[j-1]) continue;
            int k = j+1, l = size-1;
            while(k < l){
                int s = nums[i] + nums[j] + nums[k] + nums[l];
                if(s > target) l--;
                else if(s < target) k++;
                else {
                    result.push_back({nums[i], nums[j], nums[k], nums[l]});
                    while(k<l && nums[k] == nums[++k]);
                    while(k<l && nums[l] == nums[--l]);
                }
            }
        }
    }
    return result;
}