LeetCode题解——3Sum Closest
2015-07-14 19:58
429 查看
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.
只要理解了前一道3sum的题,这道题就迎刃而解[/code]
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).
class Solution { public: int threeSumClosest(vector<int>& nums, int target) { int ans = nums[0]+nums[1]+nums[2]; int sum; sort(nums.begin(),nums.end()); for(int i=0; i<nums.size()-1;i++) { int lo = i+1; int hi = nums.size()-1; while(lo<hi) { sum = nums[lo]+nums[hi]+nums[i]; if(sum==target) return target; else if(sum>target) { ans=(sum-target)>abs(ans-target)?ans:sum; hi--; } else{ ans=-(sum-target)>abs(ans-target)?ans:sum; lo++; } } } return ans; } };
只要理解了前一道3sum的题,这道题就迎刃而解[/code]
相关文章推荐
- Ubuntu adb 找不到设备的解决方法
- mongodb实践
- shell脚本编程之“最简单的死循环”
- 【java】Thread类和Runnable接口
- [SHELL]监控LINUX目录文件变化
- 字典与model
- [LeetCode][Java] Rotate Image
- C10_动态内存分配
- 云计算和大数据时代网络技术揭秘(二)云与网的关系
- ssh连接远程主机执行脚本的环境变量问题
- cf dp B. Maximum Submatrix 2
- C语言--程序设计基础——4、5章
- 不少程序员都会碰到的三个面试题
- Chapter06-Phylogenetic Trees Inherited(POJ 2414)(减少国家DP)
- ASCII
- 1. 矩形的渲染与绘制
- NSString NSArray的用法
- C9_结构体指针
- SQLite学习笔记20150714
- iOS中 @synthesize 和 @dynamic 区别