16. 3Sum Closest
16. 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).
解析
// three sum closest
class Solution_16 {
public:
// 三个指针操作O(N^2) test=([0,2,1,-3] 1);([1,1,-1,-1,3]-1)
int threeSumClosest(vector<int>& nums, int target) {
if (nums.size() < 3)
{
return 0;
}
int closest_sum = nums[0] + nums[1] + nums[2];
sort(nums.begin(), nums.end());
for (int first = 0; first < nums.size() - 2; first++)
{
if (first > 0 && nums[first] == nums[first - 1])
{
continue;
}
int second = first + 1;
int end = nums.size() - 1;
while (second<end)
{
int temp = nums[first] + nums[second] + nums[end];
if (abs(closest_sum - target)>abs(temp - target))
{
closest_sum = temp;
}
if (temp == target)
{
return temp;
}
else if (temp < target)
{
second++;
}
else
{
end--;
}
}
}
return closest_sum;
}
// 暴力O(n^3)
int threeSumClosest_1(vector<int> &num, int target)
{
int res = num[0] + num[1] + num[2];
for (int i = 0; i < num.size() - 2; i++){
for (int j = i + 1; j < num.size() - 1; j++){
for (int t = j + 1; t < num.size(); t++){
int tem = num[i] + num[j] + num[t];
if (abs(target - tem) < abs(target - res))
res = tem;
if (res == target)
return res;
}
}
}
return res;
}
};
题目来源
C/C++基本语法学习
STL
C++ primer
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 新年开篇:在本地部署DeepSeek大模型实现联网增强的AI应用
· DeepSeek火爆全网,官网宕机?本地部署一个随便玩「LLM探索」
· Janus Pro:DeepSeek 开源革新,多模态 AI 的未来
· 上周热点回顾(1.20-1.26)
· 【译】.NET 升级助手现在支持升级到集中式包管理
2017-01-20 2016回顾2017展望