JasonChang

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

similar with 3Sum

 1 public class Solution {
 2     public int threeSumClosest(int[] num, int target) {
 3         // IMPORTANT: Please reset any member data you declared, as
 4         // the same Solution instance will be reused for each test case.
 5         if(num == null || num.length < 3)
 6             return 0;
 7         Arrays.sort(num);
 8         int result = num[0] + num[1] + num[2];
 9         for(int i = 0; i < num.length - 2; i++){
10             int start = i + 1;
11             int end = num.length - 1;
12             while(start < end){
13                 int tmp = num[start] + num[end] + num[i];
14                 if(Math.abs(tmp - target) < Math.abs(result - target))
15                     result = tmp;
16                 if(tmp == target)
17                     return target;
18                 else if(tmp < target)
19                     start++;
20                 else
21                     end--;
22             }
23         }
24         return result;
25     }
26 }

 

 

posted on 2013-11-05 13:47  JasonChang  阅读(141)  评论(0编辑  收藏  举报