前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >No.016 3Sum Closest

No.016 3Sum Closest

作者头像
mukekeheart
发布2018-02-27 15:33:04
4450
发布2018-02-27 15:33:04
举报
文章被收录于专栏:mukekeheart的iOS之旅

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.

代码语言:javascript
复制
    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的数即可。重要的是判断逻辑的思路。代码如下:

代码语言:javascript
复制
 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 }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016-07-29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 16. 3Sum Closest
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档