3Sum Closest--leetcode

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).

Test instructions is given an array, a target, in the array to find a ternary group and the nearest target value, the problem is the previous 3Sum deformation, the difference is that the problem is not repeating elements, and set the solution is unique.

My idea is: the same as the previous 3sum, the left and right one pointer, traversing the time, there is a back and right two cursors, left from the beginning of the i+1, from the array to start, if I, left, Right three elements plus and so on target, then can be added to the list of results, if sum-target>0, then the sum is larger, right should be moved to the left, and vice versa.

Talk is cheap>>

      Public intThreesumclosest (int[] num,inttarget) {        if(num = =NULL|| Num.length < 3) {            return0; }        intMin =Integer.max_value; intRes=0;        Arrays.sort (num);  for(inti = 0; i < num.length-2; i++) {            intleft = i + 1; intright = Num.length-1;  while(Left <Right ) {                intsum = Num[i] + num[left] +Num[right];//System.out.printf (i+ "" +sum);                if(Sum = =target) {                    returnTarget; }                if(Min>=abs (sum-target)) {min= ABS (sum-target); Res=sum; }                if(sum-target>0) { Right--; }Else{ Left++; }            }        }        returnRes; }     Public intAbsinta) {        returnMath.Abs (a); }

3Sum Closest--leetcode

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.