LeetCode——016
2016-04-16 09:23
288 查看
/*
16. 3Sum Closest My Submissions QuestionEditorial Solution
Total Accepted: 74474 Total Submissions: 257407 Difficulty: Medium
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).
Subscribe to see which companies asked this question
*/
/*
解题思路:
与上一题一样还是采用定一议二策略
要找最相近的和值,比较的应该是距离即差的绝对值。但是在选后两个数的时候还是根据自然差值进行移动left或right 。特殊情况如和直接等于target,那么就直接返回0,因为没有比这更近的了。
本题在遍历的时候只是在确定第一个数的时候 采用了去重(即如果上一个数与当前数相等则忽略过去),但在寻找后两个数的时候,这个忽略操作不做也可以通过oj。
在设定res的初始值时要注意直接用nums[0]+nums[1]+nums[2], 我一开始用了INT_MAX发现不对,原因就是当target为负数时 res-target会超出整数的范围。
*/
class Solution { public: int threeSumClosest(vector<int>& nums, int target) { int res; sort(nums.begin(),nums.end()); if(nums.size()<3)return -1; res=nums[0]+nums[1]+nums[2]; for(int i=0;i<nums.size()-2;i++){ if(i==0|| (i>0 && nums[i]!=nums[i-1])){ int left=i+1,right=nums.size()-1; while(left<right){ int val=nums[left]+nums[right]+nums[i]; if(val-target==0)return target; if(abs(val-target)<abs(res-target))res=val; if(val-target<0)++left; else --right; } } } return res; } };
相关文章推荐
- PendingIntent详解
- Python多行注释技巧
- Android真机adb被酷狗等流氓软件抢占进程最好的解决办法
- p1056 能量项链
- SGU 137 Funny Strings(构造)
- git clone从远程主机克隆一个版本库
- Java POI 导出EXCEL经典实现 Java导出Excel弹出下载框
- 【杭电】[2602]Bone Collector
- Intent和PendingIntent的区别
- 大数求和
- 使用Docker快速打包和部署运行Disconf
- 使用 NuGet 管理我们的程序集 - 预发行版
- Mybatis传递多个参数
- phpstorm
- 山东省第四届ACM大学生程序设计竞赛 The number of steps 概率dp
- 在字符串中有序插入一个新字符
- 刘烨:家里官方语言是中文 听不懂娘仨说法语
- 神奇的位运算
- Metal 着色语言编程指南 四
- maven安装最佳实践