ITPub博客

首页 > 应用开发 > IT综合 > 算法3Sum Closest

算法3Sum Closest

IT综合 作者:dongyu2013 时间:2014-05-04 07:54:39 0 删除 编辑
  1. import java.util.Arrays;  
  2.   
  3. public class ThreeSumClosest {  
  4.     private int closest;  
  5.     private boolean needInit;  
  6.       
  7.     public int threeSumClosest(int[] num, int target) {  
  8.         closest = 0;  
  9.         needInit = true;  
  10.         Arrays.sort(num);  
  11.           
  12.         int i = 0;  
  13.         for (i = 0; i <= num.length - 3; i++) {  
  14.             if (i != 0 && num[i] == num[i - 1]) {  
  15.                 continue;  
  16.             }  
  17.             judgeAndPut(num, i, i + 1, num.length - 1, target);  
  18.         }  
  19.         return closest;  
  20.     }  
  21.   
  22.     private void judgeAndPut(int[] num, int i, int p, int q, int target) {  
  23.           
  24.         while (p < q) {  
  25.             int sum = num[i] + num[p] + num[q];  
  26.             if (needInit || Math.abs(sum - target) < Math.abs(closest - target)) {  
  27.                 closest = sum;  
  28.             }  
  29.             needInit = false;  
  30.               
  31.             if (sum <= target) {  
  32.                 p++;  
  33.                 while (p < q && num[p] == num[p - 1]) {  
  34.                     p++;  
  35.                 }  
  36.             } else if (sum > target){  
  37.                 q--;  
  38.                 while (p < q && num[q] == num[q + 1]) {  
  39.                     q--;  
  40.                 }  
  41.             }  
  42.         }  
  43.           
  44.     }  
  45.       
  46.     public static void main(String[] args) {  
  47.         int num[] = {0,1,2};  
  48.         System.out.println(new ThreeSumClosest().threeSumClosest(num, 3));  
  49.     }  
  50. }  

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29012686/viewspace-1153205/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: 算法4Sum
请登录后发表评论 登录
全部评论

注册时间:2013-12-25

  • 博文量
    263
  • 访问量
    238062