3Sum Closest题解
2016-01-31 22:00
309 查看
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.
翻译:
给定一个数列个一个目标target,找到三个数字,使得这三个数字之和与target最接近,返回三个数的和,假定只有唯一解
分析:
这题乍看有点蹊跷,仔细分析实际跟3sums是一样的,只不过3sums是与terget“相等”,这题是“最接近”,我们只要追加一个变量temp,初始temp取无穷大,然后每次存储abs(sum-target),最终返回最小的temp对应的sum就可以了
这里我们介绍一种新的方法,就是我们上篇文章中提及的不用辅助空间的方法
假设我们有三个指针i,j,k:
首先我们对array排序,sum=s[i]+s[j]+s[k]
i指向一个位置,i将array分成了两部分,0~i和i+1~n-1,0~i这部分是已经处理过的部分,i+1~n-1是待处理的部分
我们将j指向i+1 ;k指向n-1,然后像一次快排一样
如果sum < target,说明sum太小,此时j++让sum变大,
如果sum > target,说明sum太大,此时k–让sum变小,
如果sum==target,说明已经找到元素,返回就可以
由于每次移动指针会根据temp判断是否保存sum,最后sum保存的一定是最接近target的值:
STL中的sort()使用快排,时间复杂度为O(nlogn),又只增加了常数个变量,所以最终时间复杂度为O(n²),空间为O(1)
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).
翻译:
给定一个数列个一个目标target,找到三个数字,使得这三个数字之和与target最接近,返回三个数的和,假定只有唯一解
分析:
这题乍看有点蹊跷,仔细分析实际跟3sums是一样的,只不过3sums是与terget“相等”,这题是“最接近”,我们只要追加一个变量temp,初始temp取无穷大,然后每次存储abs(sum-target),最终返回最小的temp对应的sum就可以了
这里我们介绍一种新的方法,就是我们上篇文章中提及的不用辅助空间的方法
假设我们有三个指针i,j,k:
首先我们对array排序,sum=s[i]+s[j]+s[k]
i指向一个位置,i将array分成了两部分,0~i和i+1~n-1,0~i这部分是已经处理过的部分,i+1~n-1是待处理的部分
我们将j指向i+1 ;k指向n-1,然后像一次快排一样
如果sum < target,说明sum太小,此时j++让sum变大,
如果sum > target,说明sum太大,此时k–让sum变小,
如果sum==target,说明已经找到元素,返回就可以
由于每次移动指针会根据temp判断是否保存sum,最后sum保存的一定是最接近target的值:
class Solution { public: int threeSumClosest(vector<int>& nums, int target) { int result = 0; int temp = 99999; if (nums.size() <= 2) return NULL; sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size(); i++) { int j = i + 1; int k = nums.size() - 1; while (j < k) { int sum = nums[i] + nums[j] + nums[k]; if (sum - target == 0) return sum; if (sum - target < 0) { if (abs(sum - target) <= temp) { result = sum; temp = abs(sum - target); } j++; } if (sum - target > 0) { if (abs(sum - target) <= temp) { result = sum; temp = abs(sum - target); } k--; } } } return result; } };
STL中的sort()使用快排,时间复杂度为O(nlogn),又只增加了常数个变量,所以最终时间复杂度为O(n²),空间为O(1)
相关文章推荐
- DropDownList绑定显示数据库多个字段
- ASP.NET Core 1.0 基础与应用启动
- code vs 刺激
- apache 有哪些 开源
- 【安卓开发】JNI开发常用接口 - 1
- indexof用法
- English in January
- LEETCODE--House Robber
- PriorityQueue源码解析
- HDU 1560 DNA sequence(IDA*搜索)
- 再谈PHP、Python与Ruby
- 4.windows和Linux下创建oracleusername表空间,表,插入数据,用户管理表等操作
- Divide and conquer:Subset(POJ 3977)
- Ubuntu彻底删除mysql
- BZOJ-1050 旅行comf 并查集+乱搞
- 2016年1月英语总结
- hdu 2113 Secret Number
- 算法题汇总
- Mina的使用
- BZOJ-1050 旅行comf 并查集+乱搞