3Sum Closest

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).

和3Sum的思路基本一致,但是需要存一个different compare to target 用于进行比较。
 1 public class Solution {
 2     public int threeSumClosest(int[] num, int target) {
 3         // Note: The Solution object is instantiated only once and is reused by each test case.
 4         if(num == null || num.length < 3) return 0;
 5         Arrays.sort(num);
 6         int len = num.length;
 7         int min = Integer.MAX_VALUE;
 8         for(int i = 0; i < len - 2; i ++){
 9             int j = i + 1;
10             int h = len - 1;
11             while(h > j){
12                 int diff = target - num[i] - num[j] - num[h];
13                 if(Math.abs(diff) < Math.abs(min)) min = diff;
14                 if(diff > 0) j ++;
15                 else if(diff < 0) h --;
16                 else break;
17             }
18         }
19         return target - min;
20     }
21 }

 

posted on 2013-10-17 11:47  Step-BY-Step  阅读(162)  评论(0编辑  收藏  举报

导航