博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
3Sum Closest
阅读量:4562 次
发布时间:2019-06-08

本文共 1962 字,大约阅读时间需要 6 分钟。

3Sum Closest 

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很向,只要稍微改变一下就好了
1 public class Solution { 2     public int threeSumClosest(int[] num, int target) { 3         int result = Integer.MAX_VALUE;                    //最后返回的结果 4         int distance = Integer.MAX_VALUE; 5         Arrays.sort(num);                                 //对数组进行升序排序 6         boolean findTarget = false; 7          8         for(int i = 0; i < num.length; i++){ 9             int j = i + 1;10             int k = num.length - 1;                        //双指针11             while(j < k){12                 int sum = num[i] + num[k] + num[j];13                 if(target == sum){                        //等于target直接返回target的值14                     findTarget = true;15                     result = target;16                     break;17                 }18                 else if(sum > target){                    //sum比target大k前移,同时更新result,和距离19                     if(Math.abs(sum - target) < distance){20                         distance = Math.abs(sum - target);21                         result = sum;22                     }23                     k--;    24                 }25                 else{                                    //sum比target小,更新result和距离26                     if(Math.abs(sum - target) < distance){27                         distance = Math.abs(sum - target);28                         result = sum;29                     }30                     j++;31                 }32             }33             if(findTarget)34                 break;35         }36         37         return result;38     }39 }

 

转载于:https://www.cnblogs.com/luckygxf/p/4148691.html

你可能感兴趣的文章
【题解】1621. 未命名
查看>>
字符串加密算法
查看>>
Oracle的实例恢复解析
查看>>
UICollectionView cellForItemAt 不被调用
查看>>
巧用网盘托管私人Git项目
查看>>
python全栈脱产第19天------常用模块---shelve模块、xml模块、configparser模块、hashlib模块...
查看>>
[LeetCode] House Robber
查看>>
virtualbox中kali虚拟机安装增强功能
查看>>
java生成六位验证码
查看>>
iOS的MVP设计模式
查看>>
stringstream
查看>>
【转】HDU 6194 string string string (2017沈阳网赛-后缀数组)
查看>>
前后端分离
查看>>
渗透测试学习 一、环境搭建
查看>>
处理图片透明操作
查看>>
Postman-OAuth 2.0授权
查看>>
mac pycharm打不开问题
查看>>
iOS项目之苹果审核被拒
查看>>
java多态及tostring方法与equals方法的重写
查看>>
python 获取远程设备ip地址
查看>>