3Sum Closest Total

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).
 1 public class Solution {
 2     //len-3 len-2 len-1
 3     public int threeSumClosest(int[] num, int target) {
 4         int len = num.length;
 5         int min = Integer.MAX_VALUE;
 6         int res = 0;
 7         if(len<3) return 0;
 8         Arrays.sort(num);
 9         for(int i=0;i<=len-3;i++){
10             int start = i+1;
11             int end = len-1;
12             while(start<end){
13                 int sum = num[i]+num[start]+num[end];
14                 if(sum==target){
15                     return sum;
16                 }
17                 else if(sum<target){
18                     if(min>Math.abs(sum-target)){
19                         min = Math.abs(sum-target);
20                         res = sum;
21                     }
22                     start++;
23                 }
24                 else{
25                     if(min>Math.abs(sum-target)){
26                         min = Math.abs(sum-target);
27                         res = sum;
28                     }
29                     end--;
30                 }
31             }
32             while(i<len-3 && num[i]==num[i+1]){
33                 i++;
34             }
35         }
36         return res;
37     }
38 }
View Code

 

posted @ 2014-02-19 00:30  krunning  阅读(162)  评论(0编辑  收藏  举报