"Leetcode" 3Sum Closest Problem Solving report (Java)

Source: Internet
Author: User

Topic

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

and 3Sum problem-solving report is very similar, and the difference is not to ask for three number and is not 0, but to see whether the difference between three number and target is the smallest, just record the current optimal solution and constantly update its value can be.

"Java Code" O (n^2)

public class Solution {public int threesumclosest (int[] num, int target) {if (num = = NULL | | Num.length < 3                ) return 0;                Arrays.sort (num);        int ret = 0;        int closestdist = Integer.max_value;        int len = num.length;                        for (int i = 0; i < len-2; i++) {if (i > 0 && num[i] = = Num[i-1]) continue;            int L = i+1, r = len-1;                while (L < r) {int sum = Num[i] + num[l] + num[r];  if (sum < target) {if (Target-sum < closestdist) {closestdist = target-                        Sum                    ret = sum;                } l++; } else if (Sum > Target) {if (Sum-target < closestdist) {closestdist = s                        Um-target;                    ret = sum;                } r--; } else {//when sum = = TargeT, return sum.                return sum;    }}} return ret; }}

Error prone is to set the RET initial value to Integer.max_value, and then calculate closestdist = Math.Abs (Ret-target), which will cause overflow!!


"Leetcode" 3Sum Closest Problem Solving report (Java)

Related Article

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.