[leetcode] 【数组】16. 3Sum Closest
来源:互联网 发布:酒店前台收银软件 编辑:程序博客网 时间:2024/06/05 06:19
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).
题解
题意和3 sum类似,这里区别是取和target最近的组合,返回组合的和值。
a遍历三遍;
b排序+夹逼:
//cppclass Solution {public: int threeSumClosest(vector<int>& nums, int target) { sort(nums.begin(),nums.end()); int res=0; auto tail=nums.end(); int min_closet=INT_MAX; for(auto a=nums.begin();a!=tail-2;a++) { if(*a==*(a-1)&&a!=nums.begin()) continue; auto b=a+1; auto c=tail-1; while(b<c) { int sum=*a+*b+*c; int closet=abs(target-sum); if(closet<min_closet) { res=sum; min_closet=closet; if(closet==0) return res; } if(sum<target) b++; else c--; } } return res; }};
0 0
- [leetcode] 【数组】16. 3Sum Closest
- LeetCode 16. 3Sum Closest
- LeetCode --- 16. 3Sum Closest
- [Leetcode] 16. 3Sum Closest
- 【leetcode】16. 3Sum Closest
- [leetcode] 16. 3Sum Closest
- leetcode 16. 3Sum Closest
- leetcode 16. 3Sum Closest
- leetcode 16. 3Sum Closest
- LeetCode - 16. 3Sum Closest
- [LeetCode]16. 3Sum Closest
- LeetCode 16. 3Sum Closest
- LeetCode *** 16. 3Sum Closest
- Leetcode 16. 3Sum Closest
- leetcode 16. 3Sum Closest
- 【LeetCode】16. 3Sum Closest
- leetcode 16. 3Sum Closest
- 【leetcode】16. 3Sum Closest
- python with
- HTML5的一些术语和概念
- C# 文件的保存与读取
- [leetcode] 【数组】15. 3Sum
- Ubuntu(Linux) 下 unzip 命令使用详解
- [leetcode] 【数组】16. 3Sum Closest
- 微信开发获取code
- grunt的安装使用
- 将项目改为MRC的方法(有图有真相)
- 关于js传送json到.net后台处理
- 自定义控件
- Minimum Path Sum
- [leetcode] 【数组】18. 4Sum
- 大数据学习笔记·城市计算(3)