码迷,mamicode.com
首页 > 编程语言 > 详细

16. 3Sum Closest java solutions

时间:2016-07-05 13:46:24      阅读:172      评论: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).

 

Subscribe to see which companies asked this question

 1 public class Solution {
 2     public int threeSumClosest(int[] nums, int target) {
 3         int ans = 0,min = Integer.MAX_VALUE;
 4         Arrays.sort(nums);
 5         for(int i = 0; i < nums.length-2; i++){
 6             if(i > 0 && nums[i] == nums[i-1])
 7                 continue;
 8             for(int s = i + 1,e = nums.length-1;s < e;){
 9                 int sum = nums[i] + nums[s] + nums[e];
10                 if(Math.abs(sum - target) < min){
11                     min = Math.abs(sum-target);
12                     ans = sum;
13                 }
14                 if(sum > target) e--;
15                 else if(sum < target) s++;
16                 else return ans;
17             }
18         }
19         return ans;
20     }
21 }

 

16. 3Sum Closest java solutions

标签:

原文地址:http://www.cnblogs.com/guoguolan/p/5643114.html

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