随笔- 509  文章- 0  评论- 151  阅读- 22万 

3Sum Closest

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 };
复制代码

 

 posted on   zhuli19901106  阅读(286)  评论(2编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
点击右上角即可分享
微信分享提示