LeetCode16 3Sum Closest
2024-10-19 21:31:39
题意:
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;
}
};
最新文章
- 【腾讯Bugly干货分享】基于RxJava的一种MVP实现
- Visual C++ 的代码折叠
- PHP面试题4
- 第一周:Java基础知识总结(1)
- Redis学习笔记六:独立功能之 Lua 脚本
- windows下nginx和php环境的配置
- iptables配置——NAT地址转换
- Xcode 调试技巧-b
- DP录 (更新)
- 通过CreateOleObject控制IE
- ural1471 Distance in the Tree
- Linux与mv命令结合,移动文件至指定目录
- QEMU KVM libvirt 手册(1): 安装
- [MSSQL]表变量和临时表的区别
- nmcli工具详解
- OAuth 2和JWT - 如何设计安全的API?
- [UE4]用.csv作为配置文件
- tensorFlow 三种启动图的用法
- centos7.5下yum 安装mariadb数据库
- PAT甲题题解-1053. Path of Equal Weight (30)-dfs
热门文章
- 主机找不到vmnet1和vmnet8
- pku3277 City Horizon
- JVM性能优化,提高Java的伸缩性
- Android实例-实现扫描二维码并生成二维码(XE8+小米5)
- How to setup Wicket Examples in Eclipse
- 什么是S-OFF,什么是S-ON,HBOOT命令,玩转Android
- [iOS微博项目 - 2.2] - 在app中获取授权
- python svn
- POJ3041Asteroids(二分图最少顶点覆盖)
- 1) data-options