3Sum Closest: Find the sum of the three numbers in the sequence that is Closest to the given value.

Source: Internet
Author: User

3Sum Closest: Find the sum of the three numbers in the sequence that is Closest to the given value.

That is, find min {target-a-B-c} a, B, c blog to Set S;

(1) The simplest way is to find all the three distinct numbers and save them to the set, and then use target, target (+/-) I, I [0...]

The complexity is basically O (n ^ 3 ).

Int threeSumClosest (vector
 
  
& Num, int target) {int n = num. size (); if (n <3) return 0; unordered_set
  
   
Sum; for (int I = 0; I
   
    

(2) with a simple solution, we need to optimize it.

(1) A triple loop can certainly be killed, that is, first store the subscript of the two numbers and their corresponding to the map.

(2) map the map with the number of arrays. The first is a [I] + 0, then a [I] + 1, which is increased in sequence and will always be found.

(3) This is basically O (N ^ 2.

int threeSumClosest(vector
     
       &num, int target) {     int n=num.size();     if(n<3) return 0;     unordered_map
      
       > num0;     for(int i=0 ; i
       
        

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.