2014.2.25 19:02
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).
Solution:
This problem is a variation from 3Sum. In that problem, an O(n^2) algorithm was mentioned.
At first I tried to sort the array and do binary searches, but got an TLE. Then I knew it would still be O(n^2) in time complexity.
There has to be a minor adjustment for the code of "3Sum". When performing the linear scan from both ends, we not only look for exact match, but also record every sum that is closer to the target. At the end of the search, there will either be a closest sum to the target, or the target value itself.
Time complexity is O(n^2), space complextiy is O(1).
The array is not sorted, so extra O(n * log(n)) time is needed for sorting.
Accepted code:
1 // 2TLE, 1AC, O(n^2) solution, linear scan is faster than binary search. 2 #include <algorithm> 3 using namespace std; 4 5 class Solution { 6 public: 7 int threeSumClosest(vector<int> &num, int target) { 8 int n = (int)num.size(); 9 if (n < 3) { 10 return 0; 11 } 12 13 int i, j, k; 14 int res; 15 int sum; 16 17 // sort the array for linear scan 18 sort(num.begin(), num.end()); 19 // intialize with whatever result here 20 res = num[0] + num[1] + num[2]; 21 for (i = 0; i < n; ++i) { 22 j = i + 1; 23 k = n - 1; 24 while (j < k) { 25 sum = num[i] + num[j] + num[k]; 26 if (sum < target) { 27 ++j; 28 if (myabs(sum - target) < myabs(res - target)) { 29 res = sum; 30 } 31 } else if (sum > target) { 32 --k; 33 if (myabs(sum - target) < myabs(res - target)) { 34 res = sum; 35 } 36 } else { 37 return target; 38 } 39 } 40 } 41 42 return res; 43 } 44 private: 45 int myabs(const int n) { 46 return (n >= 0 ? n : -n); 47 } 48 };
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)