16.3Sum Closest (two-pointers)

Source: Internet
Author: User

Given an array S of n integers, find three integers in S such so the sum is closest to a give n 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).
classSolution { Public:    intThreesumclosest (vector<int>& Nums,inttarget) {        intSize =nums.size ();        Sort (Nums.begin (), Nums.end ()); Diff=Int_max;  for(inti =0; I < size-2; i++){            if(i>0&& nums[i]==nums[i-1])Continue; Find (Nums, I+1, size-1, target-Nums[i]); if(diff = =0)returnTarget; }        returntarget+diff; }          voidFind (vector<int>& Nums,intStartintEndinttarget) {        intsum;  while(start<end) {Sum= nums[start]+Nums[end]; if(Sum = =target) {diff=0; return; }            Else if(sum>target) {                 Do{End--; } while(End!=start && nums[end] = = nums[end+1]); if(Sum-target < ABS (diff)) diff = sum-Target; }            Else{                 Do{Start++; } while(start!= end && Nums[start] = = nums[start-1]); if(Target-sum < ABS (diff)) diff = Sum-target;//not only in the final check: there may be this situation, the previous sum>target, this sum<target, and the next time start==end, then it is likely that the previous sum is closer to the target than this sum            }        }    }Private:    intDiff//How much bigger is the sum};

16.3Sum Closest (two-pointers)

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.