3sum,16. 3Sum closest,18. 4Sum (last method important) important

Source: Internet
Author: User
Tags abs array sort int size set set

The first question, 15. 3Sum
Given an array S of n integers, is there elements a, B, C in S such that A + B + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:the solution set must not contain duplicate triplets.

For example, given array S = [-1, 0, 1, 2,-1,-4],

A Solution set is:
[
[-1, 0, 1],
[-1,-1, 2]
]
The idea of two-point search

vector<vector<int> > Threesum (vector<int> &num) {vector<vector<int> > ret;
        int size = Num.size ();
        Sort (Num.begin (), Num.end ()); for (int i = 0; i < size; I + +) {//skip same I while (i > 0 && i < size &A
            mp;& Num[i] = = Num[i-1]) i + +;
            Int J = i + 1;
            int k = size-1;
                while (J < k) {int sum = Num[i] + num[j] + num[k];
                    if (sum = = 0) {vector<int> cur (3);
                    Cur[0] = Num[i];
                    CUR[1] = Num[j];
                    CUR[2] = num[k];
                    Ret.push_back (cur);
                    j + +;
                    K--;
                    Skip Same J while (J < k && Num[j] = = Num[j-1]) j + +; Skip Same k WHile (k > J && num[k] = = num[k+1]) K--;

                } else if (Sum < 0) {j + +;

                } else {k--;
    }}} return ret; }

The second question: 3Sum Closest
Given An array S of n integers, find three integers in S such so the sum is Closest to a GI Ven number, target. Return the sum of the three integers. You may assume this each input would has exactly one solution.
For example, given array S = {-1 2 1-4}, and target = 1. The sum of
is closest to the target is 2. (-1 + 2 + 1 = 2).

int Threesumclosest (vector<int>& nums, int target) {vector<vector<int> > ret;
        int size = Nums.size ();
        Sort (Nums.begin (), Nums.end ());
        int sum = nums[0]+nums[1]+nums[size-1];
        int mindis = Sum-target;
            for (int i = 0; i < size; i++) {Int J = i + 1;
            int k = size-1;
                while (j<k) {sum = Nums[i]+nums[j]+nums[k];
                if (ABS (Sum-target) < ABS (Mindis)) {Mindis = Sum-target;
                }//mindis = Sum-target; if (sum = = target)//increase this part of the processing, is for {1,2,3,4,5,6,7} target=10, this once found 1,2,7 three number, then do not continue to traverse, continue {RE
                Turn target;
                } else if (Sum > Target) {k--;
                } else {j + +; }
            }
        } return Mindis + target; }

The third question, 18. 4Sum
Given an array S of n integers, is there elements a, B, C, 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]
]

/* Array sort determines that the first two (a, b) of the four-tuple traversal of the remaining array determines two out of two (c,d), and the idea of the CD is the same as when the 3Sum determines the two data, the binary finds the left and right approximation. Set Set */vector<vector<int>> foursum (vector<int>& nums, int target) {VECTOR&L
        t;vector<int>> result;
        Set<vector<int>> Setres;
        int len = Nums.size ();
        Sort (Nums.begin (), Nums.end ());
        if (Len < 4) {return (vector<vector<int>> ()); 
        }/* for (int i = 0, i < len; i++) {for (int j = i + 1; j < Len; j + +) */
                for (int i = 0, i < len-3; i++) {for (int j = i + 1; j < Len-2; J + +) {
                Two-point lookup int begin = j + 1;
                int end = Len-1;
                    while (begin < end) {int sum = Nums[i] + nums[j] + Nums[begin] + nums[end];
               if (sum = = target) {         Vector<int> temp;
                        Temp.push_back (Nums[i]);
                        Temp.push_back (Nums[j]);
                        Temp.push_back (Nums[begin]);
                        Temp.push_back (Nums[end]);
                        Setres.insert (temp);
                        begin++;
                    end--;
                    } else if (Sum > Target) {end--;
                    } else {begin++;
        }}}} Set<vector<int>>::iterator iter;
        for (iter = Setres.begin (); Iter!=setres.end (); iter++) {result.push_back (*iter);

    } return result; }

Code with a lower time complexity:

Vector<vector<int>> foursum (vector<int>& nums, int target) {vector<vector<int>>
        Total
        int n = nums.size ();
        if (n<4) return total;
        Sort (Nums.begin (), Nums.end ());
            for (int i=0;i<n-3;i++) {if (i>0&&nums[i]==nums[i-1]) continue;
            if (nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target) break;
            if (nums[i]+nums[n-3]+nums[n-2]+nums[n-1]<target) continue;
                for (int j=i+1;j<n-2;j++) {if (j>i+1&&nums[j]==nums[j-1]) continue;
                if (nums[i]+nums[j]+nums[j+1]+nums[j+2]>target) break;
                if (nums[i]+nums[j]+nums[n-2]+nums[n-1]<target) continue;
                int left=j+1,right=n-1;
                    while (left<right) {int sum=nums[left]+nums[right]+nums[i]+nums[j];
                    if (sum<target) left++;
    else if (sum>target) right--;                else{total.push_back (Vector<int>{nums[i],nums[j],nums[left],nums[right]}); do{left++;}
                        while (nums[left]==nums[left-1]&&left<right); do{right--;}
                    while (nums[right]==nums[right+1]&&left<right);
    }}}} return total; }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.