Leetcode #16 3Sum closest find the sum of 3 and the closest problem-solving section

Source: Internet
Author: User
Tags abs
1 Topic Understanding

Last night to patronize the late night bubble noodles, forgot to update the. So this is even more to make up for yesterday's, the other day.

This problem is similar to the Leetcode #15 3Sum three number of reconciliation, the difference is #15 is to three number and equal to the target value, this problem is the closest to the

Practice is the same, we can point to see,
Also select a benchmark and then set the head and tail to move closer to the middle

The only difference is: always judge whether the closest value appears. 2 Original question

3Sum closest
Given an array S of n integers, find three integers in s such so the sum is closest to a Given number, target. Return the sum of the three integers. You may assume this each input would have 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).
3 AC Solution

I am the code that copied the previous question. Ha ha

public class Solution {/** * is actually a copy of the previous question * * */public int threesumclosest (int[
        ] nums, int target) {arrays.sort (nums);
        int i,j,k,result=0,reserve;
        int min=integer.max_value;
            for (i=0;i<nums.length-2;i++) {j=i+1;
            Reserve=target-nums[i]; while (j<k) {if (Math.Abs (reserve-nums[j]-nums[k)) <min) {Result=nums[i]+nums[j]+nu
                Min=math.abs (Reserve-nums[j]-nums[k]);
                } if (Nums[j]+nums[k]<reserve) {j + +;
                } else{k--;
    }} return result; }

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.