3Sum Closest
来源:互联网 发布:黑客帝国进入矩阵 编辑:程序博客网 时间:2024/06/08 06:48
class Solution {public: int threeSumClosest(vector<int> &num, int target) { int result; int gap = INT_MAX; sort(num.begin(), num.end()); for(int i=0; i<num.size()-2; i++) { if(i>0 && num[i] == num[i-1]) continue; int left = i+1; int right = num.size()-1; while(left < right) { auto sum = num[i] + num[left] + num[right]; if(abs(target-sum) < gap) { gap = abs(target-sum); result = sum; } if(sum < target) left++; else if(sum > target) right--; else return result; //this branch cannot be neglect, otherwise //there would be infinite loop with example [0 1 2] 3 } } return result; }};
排序后左右夹逼,时间O(n^2)。
8.23最新代码:
class Solution {public: int threeSumClosest(vector<int> &num, int target) { int gap = INT_MAX; int real = 0; int ret = 0; std::sort(num.begin(), num.end()); for(int i=0; i<num.size()-2; i++) { if(i>0 && num[i] == num[i-1]) continue; int left = i+1; int right = num.size()-1; while(left < right) { if(left > i+1 && num[left] == num[left-1]) { left++; continue; } if(right < num.size()-1 && num[right] == num[right+1]) { right--; continue; } real = num[i] + num[left] + num[right]; if(gap > abs(real-target)) { gap = abs(real - target); ret = real; } if(real < target) left++; else if(real > target) right--; else { return ret; } } } return ret; }};
0 0
- 3 Sum & 3 Sum Closest
- 【Leetcode】3Sum Closest (Sum)
- LeetCode: 3 Sum Closest
- 3Sum Closest
- leetcode - 3 sum closest
- leetcode 3Sum Closest
- LeetCode: 3Sum Closest
- [Leetcode]3Sum Closest
- Leetcode: 3SUM Closest
- LeetCode 3Sum Closest
- [Leetcode] 3Sum Closest
- leetcode002:3sum closest
- LeetCode : 3Sum Closest
- LeetCode 3Sum Closest
- 3Sum Closest
- 3Sum Closest
- 3Sum Closest
- [LeetCode] 3Sum Closest
- 搜索专题之BFS
- hbase安装
- 验科岗位来
- 浅谈HTTP中Get与Post的区别
- RGB颜色查询对照表
- 3Sum Closest
- 面向对象----C#运算符重载
- A. Winner Codeforences
- 如何聚集高水平研发人员
- 视图调用存储过程全局变量
- 使用EF6和MVC5实现一个简单的选课系统--使用EF6实现继承(11/12)
- Java synchronized详解
- SEO时代已成为过去,??已经到来
- STL源码剖析笔记