Leetcode122: 3Sum Closest
2015-10-27 15:11
281 查看
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.
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 n = nums.size(); int mindiff = INT_MAX; int res; sort(nums.begin(), nums.end()); for(int i = 0; i < n-2; i++) { if(i>0 && nums[i]==nums[i-1]) continue; int j = i+1; int k = n-1; while(j<k) { int sum = nums[i]+nums[j]+nums[k]; if(sum<target) { if((target-sum)<mindiff) { mindiff = target-sum; res = sum; } j++; } else if(sum>target) { if((sum-target)<mindiff) { mindiff = sum-target; res = sum; } k--; } else return sum; } } return res; } };
相关文章推荐
- mysql导入csv格式数据
- 什么是 MIME Type?
- Eclipse 安装Svn 插件
- testlink于smarty配置和使用
- java调用Command命令
- PowerDesigner设计数据库
- ——黑马程序员——C语言基础--强制类型转换
- 究竟应该怎样写博客
- eclipse 笔记
- Android Crash
- web.xml中url-pattern匹配规则
- 一个Java程序员应该掌握的10项技能
- OC --- KVC
- linuxc_螺纹锁紧pthread_mutex_t
- XmlSerializer 对象的Xml序列化和反序列化,XMLROOT别名设置
- iOS设置处理异常的方法
- android 图片加载和缓存开源项目 Picasso
- 每日一个OpenGL API (二)
- NDK搭建环境笔记
- 河南夏邑县卫生局容灾智能鼎