码迷,mamicode.com
首页 > 其他好文 > 详细

3Sum Closest

时间:2016-04-27 09:25:31      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:

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 would 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).
相关题目:2sum,3sum
sum < target 能直接 ++left 是因为--right 会 扩大其与target 的距离。
注意:防止溢出。
 1 public class Solution {
 2     public int threeSumClosest(int[] nums, int target) {
 3         Arrays.sort(nums);
 4         long closest = Integer.MAX_VALUE;
 5         for (int i = 0; i < nums.length - 2; i++) {
 6             int left = i + 1;
 7             int right = nums.length - 1;
 8             int sum = 0;
 9             while (left < right) {
10                 sum = nums[i] + nums[left] + nums[right];
11                 if (sum == target) {
12                     return sum;
13                 } else if (sum < target) {
14                     ++left;
15                 } else {
16                     --right;
17                 }
18                 closest = Math.abs(sum - target) < Math.abs(closest - target) ? sum : closest;
19             }
20         }
21         return (int)closest;
22     }
23 }

 

3Sum Closest

标签:

原文地址:http://www.cnblogs.com/FLAGyuri/p/5437472.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!