4 Sum LeetCode

 4 Sum

Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:

  • 0 <= a, b, c, d < n
  • abc, and d are distinct.
  • nums[a] + nums[b] + nums[c] + nums[d] == target

You may return the answer in any order.

 

Example 1:

Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]

Example 2:

Input: nums = [2,2,2,2,2], target = 8
Output: [[2,2,2,2]]

 

Constraints:

  • 1 <= nums.length <= 200
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
Solution To the Above Question

class Solution
{
public:
    vector<vector<int>> fourSum(vector<int&numsint target)
    {

        sort(nums.begin(), nums.end());
        int n = nums.size();
        // for(int i=0; i<n; i++){
        //     cout<<nums[i]<<" ";
        // }
        cout << endl;
        vector<vector<int>> ans;
        vector<int> v;
        if (nums.size() < 4)
        {
            return ans;
        }
        for (int i = 0; i < n - 3; i++)
        {

            for (int x = i + 1; x < n - 2; x++)
            {

                int j = x + 1;
                int k = n - 1;
                while (j < k)
                {
                    long long int current = nums[i];
                    current += nums[x];
                    current += nums[j];
                    current += nums[k];
                    // cout<<current<<" ";
                    if (current == target)
                    {
                        v.push_back(nums[i]);
                        v.push_back(nums[x]);
                        v.push_back(nums[j]);
                        v.push_back(nums[k]);
                        bool flag = false;
                        for (int m = 0; m < ans.size(); m++)
                        {
                            if (ans[m] == v)
                            {
                                flag = true;
                            }
                        }
                        if (!flag)
                        {
                            ans.push_back(v);
                        }

                        v.clear();
                        j++;
                    }
                    else if (current > target)
                    {
                        k--;
                    }
                    else if (current < target)
                    {
                        j++;
                    }
                }
            }
        }
        return ans;
    }
};

Post a Comment

0 Comments