【LeetCode算法练习(C++)】3Sum Closest
来源:互联网 发布:工信部域名备案系统 编辑:程序博客网 时间:2024/06/05 04:34
题目:
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).
链接:3Sum Closest
解法:排序,用一对指针j,k搜索,三个数的和如果大于target,需要左移k,如果小于target,需要右移j,遍历i从最小到最大。时间O(n^2)
class Solution {public: int threeSumClosest(vector<int>& nums, int target) { int sum = 0, ans = INT_MAX / 2, len = nums.size(); sort(nums.begin(), nums.end()); for (int i = 0; i < len - 2; i++) { int j = i + 1, k = len - 1; while (j < k) { int sum = nums[i] + nums[j] + nums[k]; ans = abs(sum - target) < abs(ans - target) ? sum : ans; if (sum < target) { ++j; } else if (sum > target) { --k; } else { ++j; --k; } } } return ans; }};
Runtime: 16 ms
阅读全文
0 0
- 【LeetCode算法练习(C++)】3Sum Closest
- 【LeetCode算法练习(C++)】3Sum
- leetcode 3 sum closest算法
- leetcode - 3Sum Closest (kSum Closest)
- 【LeetCode算法练习(C++)】4Sum
- 【LeetCode算法练习(C++)】Combination Sum
- LeetCode OJ算法题(十六):3Sum Closest
- Leetcode c语言-3Sum Closest
- 【LeetCode016-017算法/编程练习C++】3Sum Closest,九宫格输入法//Sort函数
- 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
- 与其他应用交互 Intent
- 点击按钮进行QQ交谈
- 通过intent跳转到系统拨号页面
- jxl excel导出
- Android样式的开发:shape篇
- 【LeetCode算法练习(C++)】3Sum Closest
- 【OpenGL】用Bresenham算法画线
- Android 静默安装 静默卸载 探索之路
- JAVA运算符
- MySQL数据库自动添加时间戳
- Evaluate Division问题及解法
- android仿微信图片选择器
- Android系统自带样式(@android:style/)
- 3-4 计算长方形的周长和面积