Leetcode | | 3Sum Closest problem

Source: Internet
Author: User

Problem:

Given an array S of n integers, find three integers in S such, the sum was closest to a Given 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 is closest to the target is 2. (-1 + 2 + 1 = 2).

Given an array, the number of three numbers is closest to the target, and the result is nearly the default unique


Thinking:

(1) is not very familiar, this problem is only to seek three number and for a specific value of the deformation

(2) still use greedy thought , three-pointer binary search, look for three number and the absolute value of the difference with the minimum sum of the values, the flag is used in the positive and negative relationship .

Code:

Class Solution {Public:int threesumclosest (vector<int> &num, int target) {int index;    BOOL Flag=true;        Sort (Num.begin (), Num.end ());        if (num.at (0) +num.at (1) +num.at (2) >target) index=num.at (0) +num.at (1) +num.at (2)-target;                else {index=target-(num.at (0) +num.at (1) +num.at (2));            Flag=false;            } for (int i = 0; i < num.size (); ++i) {int p = i + 1, q = num.size ()-1;            int sum=0;                while (P < q) {sum = Num[i] + num[p] + num[q];                if (sum = = target) {return sum;                    }//if else if (sum < target)//And too small, p moves backwards {++p;                        if (target-sum<index) {index=target-sum;                    Flag=false;       }} else     And too large, Q moves forward {--q;                        if (sum-target<index) {index=sum-target;                    Flag=true;        }}//else}//while}//for if (flag) return index+target;    else return target-index; }};<strong></strong>


Leetcode | | 3Sum Closest problem

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.