[Leetcode] 3Sum Closest

Source: Internet
Author: User

1 topics

Given an array S of N integers, find three integers in S such the sum is 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).

2 Ideas

Well, after a few months did not brush, the problem did a very painful, spent 4, 5 hours. First of all, the problem of understanding the meaning of the wrong, and then understand the situation, the idea is wrong again. Have to look at other people's answers.

The best way to solve this problem is O (n^2).

Since the requirement of time complexity is O (n^2), then the idea is good to run. Traverse all 3 combinations to see which one is the closest to target. The method used is a head pointer, a tail pointer, a current pointer, details, see the code.

3 Code

     Public intThreesumclosest (int[] Nums,inttarget) {        intsum = 0; if(Nums.length <= 3)        {             for(inti:nums) {Sum+=i; }            returnsum;        } arrays.sort (Nums); Sum= Nums[0]+nums[1]+nums[2]; intAdd =sum;  for(inti = 0; i < nums.length-2; i++) {            intHead = i+1; intEnd = Nums.length-1;  while(Head <end) {Add= Nums[i] + Nums[head] +Nums[end]; if(Add <target) {Head++; }Else{End--; }                                if(Math.Abs (Add-target) < Math.Abs (sum-target)) {Sum=add; }            }        }        returnsum; }

Henceforth, as far as possible, two days one question.



[Leetcode] 3Sum Closest

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.