16. 3Sum Closest java solutions

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 }

 

posted @ 2016-07-05 11:48  Miller1991  阅读(135)  评论(0编辑  收藏  举报