3Sum Closest--LeetCode
来源:互联网 发布:linux安装windows软件 编辑:程序博客网 时间:2024/05/16 19:12
1.题目
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).
2.题意
求最接近target的三数之和
假定每个输入都只有一个解决方案
3.分析
要保证三数和跟target差的绝对值最小
brute force时间复杂度为O(n^3)
优化的解法是先排序再左右夹逼
我们需要定义一个变量diff用来记录差的绝对值
先确定一个数,再滑动寻找另外两个数
每确定两个数,求出此三数之和
再算和target的差的绝对值存在newDiff中
然后和diff比较并更新diff和结果result即可
总的时间复杂度为O(n^2+nlogn)=(n^2),空间复杂度是O(1)
一定要特别注意不要遗漏sort(nums.begin(), nums.end());
4.代码
class Solution {public: int threeSumClosest(vector<int>& nums, int target) { int result = nums[0] + nums[1] + nums[2]; int diff = abs(result - target); sort(nums.begin(), nums.end()); for(int i = 0; i < nums.size() - 2; ++i) { int j = i + 1; int k = nums.size() - 1; while(j < k) { int sum = nums[i] + nums[j] + nums[k]; int newDiff = abs(sum - target); if(newDiff < diff) { result = sum; diff = newDiff; } if(sum < target) ++j; else --k; } } return result; }};
阅读全文
0 0
- LeetCode: 3 Sum Closest
- leetcode - 3 sum closest
- leetcode 3Sum Closest
- LeetCode: 3Sum Closest
- [Leetcode]3Sum Closest
- Leetcode: 3SUM Closest
- LeetCode 3Sum Closest
- [Leetcode] 3Sum Closest
- LeetCode : 3Sum Closest
- LeetCode 3Sum Closest
- [LeetCode] 3Sum Closest
- 【leetcode】3Sum Closest
- [LeetCode]3Sum Closest
- LeetCode-3Sum Closest
- LeetCode:3Sum Closest
- LeetCode | 3Sum Closest
- 【leetcode】3Sum Closest
- Leetcode: 3Sum Closest
- Hibernate 一级缓存,二级缓存,查询缓存
- Linux进程的共享文件
- 倒计时工具类:PYContDownManager
- android 内存监测工具 DDMS 和mat 工具使用
- include指令和动作的区别
- 3Sum Closest--LeetCode
- 【SSM】Eclipse使用Maven创建Web项目+整合SSM框架(这个666)
- 初识Runtime之KVO实现原理
- 产品级框架封装-单例模版
- Java 生成随机中文、英文姓名(上)
- Maven-简介与安装
- 前端css,修饰类,div,段落等的方法
- javaIO流出现乱码解决方法
- HDU 4494 Teamwork(最大流-Dinic+最小费用最大流-mcmf)