3Sum Closest
来源:互联网 发布:淘宝口令红包怎么领 编辑:程序博客网 时间:2024/05/29 18:14
Given an array S of n integers, find three integers inS 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).
int threeSumClosest(vector<int> &num, int target){ const int MAX_INT = ((unsigned)(-1)>>1); sort(num.begin(), num.end()); int min_ans = 0; int min_val = MAX_INT; for(int i = 0; i < (int)num.size() - 2; i++) { if(i >= 1 && 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; } if(num[i] + num[left] + num[right] < target) { int val = target - (num[i] + num[left] + num[right]); if(val < min_val) { min_val = val; min_ans = num[i] + num[left] + num[right]; } left++; } else if(num[i] + num[left] + num[right] > target) { int val = (num[i] + num[left] + num[right]) - target; if(val < min_val) { min_val = val; min_ans = num[i] + num[left] + num[right]; } right--; } else { min_ans = target; min_val = 0; left++; right--; } } } return min_ans;}
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
- Nico Website
- 在二维数组中查找指定的序列是否存在
- vs2012警告未能加载包“visual c++ package”
- xcode5 xcode6 xcode6.2beta网盘下载地址
- Java高精度打印
- 3Sum Closest
- web开发中关于中文乱码的解决方案
- 4Sum
- java设置图像dpi
- Unity3D【脚本】鼠标对摄像机的控制 - 点击鼠标,摄像机围绕圆心旋转(第三次修改)
- OC语法<4.7> Foundation框架中的-日期操作
- java 取整函数总结
- 最初的梦想
- android读取本地网页