leetcode_c++:3Sum Closest(016)
来源:互联网 发布:淘宝羊毛衫 编辑:程序博客网 时间:2024/06/06 02:06
题目
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).
算法
还是先排序,再左右夹逼。复杂度:(0(n*n))
class Solution {public: int threeSumClosest(vector<int> &num, int target) { int ret = num[0] + num[1] + num[2]; int len = num.size(); sort(num.begin(), num.end()); for (int i = 0; i <= len - 3; i++) { // first number : num[i] int j = i + 1; // second number int k = len - 1; // third number while (j < k) { int sum = num[i] + num[j] + num[k]; if (abs(sum - target) < abs(ret - target)) ret = sum; if (sum < target) { ++j; } else if (sum > target) { --k; } else { ++j; --k; } } } return ret; }};
0 0
- leetcode_c++:3Sum Closest(016)
- 016 - 3Sum Closest
- 016 3Sum Closest
- leetcode_c++:4sum(016)
- leetcode_c++:3Sum(015)
- LeetCode 016 3Sum Closest
- LeetCode 016 3Sum Closest
- LeetCode 016 3Sum Closest
- [LeetCode]016-3Sum-Closest
- LeetCode 016 3Sum Closest
- LeetCode 016 3Sum Closest
- LeetCode-016 3Sum Closest
- leetcode 016 —— 3Sum Closest
- 【LeetCode OJ 016】3Sum Closest
- 【LeetCode OJ 016】3Sum Closest
- leetcode解题方案--016--3 sum closest
- 3 Sum & 3 Sum Closest
- 【Leetcode】3Sum Closest (Sum)
- Unlucky Number I
- PS基础知识二
- ML_Liner Regression[机器学习]
- 开始学习HANA: In-memory Computing with SAP HANA on Lenovo X6 Systems
- linux 下查看系统资源和负载,以及性能监控
- leetcode_c++:3Sum Closest(016)
- Windows 08R2_破解管理员密码
- Hue-安装-配置-添加Oozie
- 【LeetCode】113. Path Sum II 基于Java和C++的解法及分析
- 679 - Dropping Balls
- Binder学习笔记(二)——defaultServiceManager()返回了什么?
- PS基础知识三
- Java内部类引用外部类中的局部变量为何必须是final问题解析
- 跟我一起学习MySQL技术内幕(第五版):(第三章学习日记4)