3Sum Closest
2015-07-08 20:07
363 查看
描述
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).
中文:
返回最接近三个数据的result,确保是唯一的解。返回三个整数的和。
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).
中文:
返回最接近三个数据的result,确保是唯一的解。返回三个整数的和。
class Solution { public: int threeSumClosest(vector<int> &num, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function int size = num.size(); if (size < 3) { return 0; } sort(num.begin(), num.end()); // 对于以下的处理过程必须事先排序,类似二分搜索 int result = 0; // 记录最终结果 int distance = INT_MAX; // signed int int sum = 0; // 中间结果 int i = 0, j , k ; for(i = 0; i < size - 2; i++) // 三元组的第一个元素一次遍历,范围为[0...n-3] { // 去重避免重复计算,如果和上次同则跳过 if (i > 0 && num[i] == num[i-1]) { continue; } j = i + 1; // 选定三元组第一个元素后,第二个元素从第一个元素的下一个位置开始考察 k = size - 1; // 选定三元组第一个元素后,第三个元素从数组末尾开始考察 while (j < k) // 三元组的后两个元素利用左右逼近来跳过效率,选定第一个元素后,其后的所有元素只需考察一遍 { sum = num[i] + num[j] + num[k]; if (sum == target) // 存在距离最近为0则直接返回,否则穷举选取非0最小距离 { return sum; } else if(sum < target) { if((target - sum) < distance) { result = sum; distance = target - sum; } j = j + 1; // 避免重复计算,如果和上次同则跳过 if (num[j] == num[j-1]) { j = j + 1; } } else if(sum > target) { if((sum - target) < distance) { result = sum; distance = sum - target; } k = k - 1; // 避免重复计算如果和上次同则跳过 if (num[k] == num[k+1]) { k = k -1; } } } } return result; } };
相关文章推荐
- poj 2724 Purifying Machine (最小边覆盖)
- 凸优化:ADMM(Alternating Direction Method of Multipliers)交替方向乘子算法系列之八: Distributed Model Fitting
- pwd命令
- GDB调试详解
- leetcode 013 —— Roman to Integer
- 64位Ubuntu-12.04 系统更新时总报错,软件中心也打不开
- touch命令
- BZOJ 2005 能量采集
- Lucas的数论题解
- 安装伪分布式hbase 0.99.0
- 最大子数组和
- windows 2012我的电脑在桌面显示
- 易經大意原稿(頁單位) 001-025
- Command模式
- [转]LAMP 系统性能调优,第 3 部分: MySQL 服务器调优
- linux 开启支持FrameBuffer--解决打开/dev/fb0失败的问题
- Cocos2dx基础 | [cocos2dx 3.0 (一)] 对文件读写操作 +FileUtils类
- 欢迎使用CSDN-markdown编辑器
- ASIHttpRequest 摘要
- 凸优化:ADMM(Alternating Direction Method of Multipliers)交替方向乘子算法系列之七: Consensus and Sharing