果果1020

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

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.

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

 

posted on 2017-01-02 22:24  果果1020  阅读(101)  评论(0)    收藏  举报