[Leetcode]3Sum Closest
来源:互联网 发布:055型驱逐舰知乎 编辑:程序博客网 时间:2024/06/05 02:49
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).
Have you met this question in a real interview?
class Solution {public: /*algorithm: two pointers */ int threeSumClosest(vector<int>& nums, int target) { int size = nums.size(); long minSum = INT_MAX; sort(nums.begin(),nums.end()); for(int i = 0;i < size - 2;i++){ int l=i+1,r = size-1; while(l < r){ int sum = nums[i] + nums[l]+nums[r]; if(abs(sum - target) < abs(minSum-target)){ minSum = sum; } if(sum == target)return target; else if(sum < target)l++; else r--; } } return minSum; }};
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
- 在C语言的库函数中就有快速排序的库函数,即为qsort
- iOS开发--OC对象模型你必须知道的几条规则
- 对话框形式的activity
- 九度OJ 1164:旋转矩阵 (矩阵运算)
- matlab 2014a的入门学习(1)周总结
- [Leetcode]3Sum Closest
- 从头认识java-4.2 方法重载
- 博客开通第一天
- Windows脚本符号总结
- 单元测试实施要点
- Contains Duplicate leetcode
- 经典语录收录(2)
- C语言:字符串的常用函数 !
- 九度OJ 1165:字符串匹配 (模式匹配)