LeetCode -- 3Sum Closest

Source: Internet
Author: User

LeetCode -- 3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. return the sum of the three integers. you may assume that each input wowould have exactly one solution.

For example, given array S = {-1 2 1-4}, and target = 1. the sum that is closest to the target is 2. (-1 + 2 + 1 = 2 ).
Original question link: https://oj.leetcode.com/problems/3sum-closest/

Question: given an array S, find the three numbers in S to bring them closer to the target value. And returns its sum.

Public int threeSumClosest (int [] num, int target) {int min = Integer. MAX_VALUE; int result = 0; Arrays. sort (num); for (int I = 0; I <num. length; I ++) {int j = I + 1; int k = num. length-1; while (j <k) {int sum = num [I] + num [j] + num [k]; int minus = Math. abs (sum-target); if (minus = 0) return sum; if (minus <min) {min = minus; result = sum;} if (sum <= target) j ++; elsek --;} 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.