码迷,mamicode.com
首页 > 其他好文 > 详细

No.016 3Sum Closest

时间:2016-07-29 22:43:57      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:

16. 3Sum Closest

  • Total Accepted: 86565
  • Total Submissions: 291260
  • Difficulty: Medium

 

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的解法有点类似,我们可以先将数组排序,然后将数组中的数从左到右依次确定为第一个数,在其右边的数中寻找最接近的target的数即可。重要的是判断逻辑的思路。代码如下:

 1 public int threeSumClosest(int[] nums, int target) {
 2     if (nums == null || nums.length < 3) {
 3         return 0;
 4     }
 5         
 6     Arrays.sort(nums);
 7     
 8     int closest = nums[0]+nums[1]+nums[2] ;
 9     
10     for(int i = 0 ; i < nums.length-2 ; i++){
11         int l = i+1 ;
12         int r = nums.length-1 ;            
13         while(l < r){
14             int sum = nums[i] + nums[l] + nums[r] ;
15             if(sum == target){
16                 return sum ;
17             }else if(sum < target){
18                 /*
19                  * 三种情况:
20                  *     1、closest < sum < target --->closest = sum
21                  *     2、sum < target < closest --->| target-sum < closest-target ---> closest = sum
22                  *                                   | target-sum >= closest-target --> closest不变
23                  *     3、sum <= closest <= target ---> closest不变
24                  */
25                 if(sum > closest){
26                     //情况1
27                     closest = sum ;
28                 }else if(closest > target){
29                     //情况2
30                     if(target-sum < closest-target){
31                         //情况2.1,
32                         closest = sum ;
33                     }
34                     //情况2.2不用变化
35                 }
36                 //情况3不同变化
37                 l++ ;
38             }else{
39                 //分析同上
40                 if(sum < closest){
41                     closest = sum ;
42                 }else if(closest < target){
43                     if(sum-target <= target-closest){
44                         closest = sum ;
45                     }
46                 }
47                 r-- ;
48             }
49         }
50         
51     }        
52     return closest ;
53 }

 

 

 

 

 

 

No.016 3Sum Closest

标签:

原文地址:http://www.cnblogs.com/mukekeheart/p/5719812.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!