LeetCode 16 3Sum Closest
2016-04-09 12:43
369 查看
16. 3Sum Closest
Total Accepted:73703 Total Submissions:
255236 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
Have you met this question in a real interview?
和3Sum那道题差不多。
这道题要找出的三个数是和target相差最小的三个数。
裸暴力枚举会妥妥超时。
可以先排个序,从左向右,每次对枚举的结果加以判断,如果当前temp>num,说明枚举的数有些大了,把最大的数下标r--,如果temp<num,说明枚举的数有些小了,把l++;
class Solution { public: int threeSumClosest(vector<int>& nums, int target) { int ret=nums[0]+nums[1]+nums[2]; sort(nums.begin(),nums.end()); int len=nums.size(); for(int i=0;i<len-2;i++) { int l=i+1,r=len-1; while(l<r) { int temp=nums[i]+nums[l]+nums[r]; if(abs(temp-target)<abs(ret-target)) ret=temp; if(temp>target) r--; else l++; } } return ret; } };
相关文章推荐
- 深度学习和自然语言处理中的注意和记忆Attention and Memory in Deep Learning and NLP
- 操作型模式之Strategy(策略)模式
- C 语言 —— debug(逻辑错误)
- 8. 表的分割
- Hadoop2.6.2 编译
- double int char 数据类型
- hdu 1081(最大子矩阵)
- oracle11g导出DMP不能导空表解决方法
- MySQL中tinytext、text、mediumtext和longtext详解
- Geekers团队成立日志
- 卷积神经网络在自然语言处理的应用Understanding Convolutional Neural Networks for NLP
- 京东2016实习生在线笔试
- ubuntu14.04安裝numpy,scipy
- Apache RewriteBase 指令使用介绍
- Eclipse中出现-访问限制由于对必需的库XX具有一定限制,因此无法访问类型
- memcached实战系列(七)理解Memcached的数据过期方式、新建过程、查找过程
- 使用Solr搭建“小”数据集群的搜索和推荐功能
- memcached实战系列(七)理解Memcached的数据过期方式、新建过程、查找过程
- android-universal-image-loader控件中遇到的bug
- Normalizing All Layers(II): Back-Propagation