博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【leetcode】3Sum Closest(middle)
阅读量:6985 次
发布时间:2019-06-27

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

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).

 

思路:

先排序,然后固定一个边界,另外两个边界收缩。

class Solution {public:    int threeSumClosest(vector
&num, int target) { int l, r, m; int ans = num[0] + num[1] + num[2]; sort(num.begin(), num.end()); //数字从小到大排序 for(l = 0; l < num.size() - 2; l++) //固定左边界 { m = l + 1; r = num.size() - 1; while(m < r) //收缩中间和右边界 { int tmp = num[l] + num[m] + num[r]; ans = (abs(ans - target) > abs(tmp - target)) ? tmp : ans; if(tmp < target) { (num[m] > num[r]) ? r-- : m++; //比目标小 则把小的数字变大 } else if(tmp > target) { (num[m] < num[r]) ? r-- : m++; //比目标大 则把大的数字变小 } else { return tmp; //已经等于target就直接返回 } } } return ans; }};

 

转载地址:http://gavpl.baihongyu.com/

你可能感兴趣的文章
基于Servlet_MVC模式增删改查_model(1)
查看>>
利用jquery的qrcode.js插件生成二维码的两种方式的使用
查看>>
Linux内存释放脚本
查看>>
京宝软件开始发布了
查看>>
网络分层协议图以及各层的简介
查看>>
socke三
查看>>
ExtJs6 理解 -- Ext.data.proxy.Proxy
查看>>
mysql开局配置
查看>>
C#深拷贝
查看>>
魅族 C++ 微服务框架技术内幕揭秘
查看>>
flask 学习笔记 mvc ,sqlalchemy(insert,update)
查看>>
HTML基础(一)
查看>>
EGOImageView 解析
查看>>
我的友情链接
查看>>
我的友情链接
查看>>
linux日常管理3
查看>>
JQ 实现点击按钮显示弹窗,点击非弹窗和按钮区域隐藏弹窗
查看>>
我的友情链接
查看>>
我的友情链接
查看>>
1.解读REST和JAX-RS
查看>>