题意:

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

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

分析:

  排序、遍历方式顺序 与3 sum思路一致,维护一个与target的差值即可。

代码:

 class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int diff = 0x7FFFFFFF;
for (int i = ; i < nums.size() - ; ++i) {
int start = i + , end = nums.size() - ;
while (start < end) {
int curSum = nums[i] + nums[start] + nums[end];
if (curSum - target == ) {
return target;
}
else if (curSum - target > ) {
if (curSum- target < abs(diff) ) {
diff = curSum - target;
}
end--;
}
else {
if (target - curSum < abs(diff)) {
diff = curSum - target;
}
start++;
}
}
}
return diff + target;
}
};

最新文章

  1. 【腾讯Bugly干货分享】基于RxJava的一种MVP实现
  2. Visual C++ 的代码折叠
  3. PHP面试题4
  4. 第一周:Java基础知识总结(1)
  5. Redis学习笔记六:独立功能之 Lua 脚本
  6. windows下nginx和php环境的配置
  7. iptables配置——NAT地址转换
  8. Xcode 调试技巧-b
  9. DP录 (更新)
  10. 通过CreateOleObject控制IE
  11. ural1471 Distance in the Tree
  12. Linux与mv命令结合,移动文件至指定目录
  13. QEMU KVM libvirt 手册(1): 安装
  14. [MSSQL]表变量和临时表的区别
  15. nmcli工具详解
  16. OAuth 2和JWT - 如何设计安全的API?
  17. [UE4]用.csv作为配置文件
  18. tensorFlow 三种启动图的用法
  19. centos7.5下yum 安装mariadb数据库
  20. PAT甲题题解-1053. Path of Equal Weight (30)-dfs

热门文章

  1. 主机找不到vmnet1和vmnet8
  2. pku3277 City Horizon
  3. JVM性能优化,提高Java的伸缩性
  4. Android实例-实现扫描二维码并生成二维码(XE8+小米5)
  5. How to setup Wicket Examples in Eclipse
  6. 什么是S-OFF,什么是S-ON,HBOOT命令,玩转Android
  7. [iOS微博项目 - 2.2] - 在app中获取授权
  8. python svn
  9. POJ3041Asteroids(二分图最少顶点覆盖)
  10. 1) data-options