16. 3Sum Closest

注意标准设定的大小不能超过Integer.MAX_VALUE

 

 1 class Solution {
 2     public int threeSumClosest(int[] nums, int target) {
 3         Arrays.sort(nums);
 4         int min = Integer.MAX_VALUE - Math.abs(target); //这里要注意 target可能是负数 所以可能会超过MAX
 5         for(int i = 0; i < nums.length - 2; i++) {
 6             int lo = i + 1, hi = nums.length-1;
 7             while(lo < hi) {
 8                 if(nums[i] + nums[lo] + nums[hi] == target) {
 9                     return target;
10                 }else if(nums[i] + nums[lo] + nums[hi] < target) {
11                     if(Math.abs(nums[i] + nums[lo] + nums[hi] - target) < Math.abs(min - target)) {
12                         min = nums[i] + nums[lo] + nums[hi];
13                     }
14                     lo++;
15                 }else {
16                     if(Math.abs(nums[i] + nums[lo] + nums[hi] - target) < Math.abs(min - target)) {
17                         min = nums[i] + nums[lo] + nums[hi];
18                     }
19                     hi--;
20                 }
21             }
22         }
23         return min;
24         
25     }
26 }

 

posted @ 2018-09-06 10:15  jasoncool1  阅读(91)  评论(0编辑  收藏  举报