3Sum Closest
来源:互联网 发布:基金产品概括 知乎 编辑:程序博客网 时间:2024/05/28 23:11
Description:
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).
#include <iostream>#include <vector>#include <algorithm>#include <cstdlib>#include <climits>using namespace std;class Solution{public: int threeSumCloset(vector<int> &num, int target) { int result= 0, min_closet=INT_MAX; sort(num.begin(),num.end()); for (auto i=num.begin(); i != num.end(); ++i) { auto j = i + 1; auto k = num.end() - 1; while (j < k) { int sum = *i + *j + *k; int difference = abs(target-sum); if (difference < min_closet) { min_closet = difference; result = sum; } if (target < sum) --k; else ++j; } } return result; }};int main(){ vector<int> num={-1,2,1,-4}; int result = 0; Solution solution; result = solution.threeSumCloset(num,1); cout<<result<<endl; return 0;}
0 0
- 3 Sum & 3 Sum Closest
- 【Leetcode】3Sum Closest (Sum)
- LeetCode: 3 Sum Closest
- 3Sum Closest
- leetcode - 3 sum closest
- leetcode 3Sum Closest
- LeetCode: 3Sum Closest
- [Leetcode]3Sum Closest
- Leetcode: 3SUM Closest
- LeetCode 3Sum Closest
- [Leetcode] 3Sum Closest
- leetcode002:3sum closest
- LeetCode : 3Sum Closest
- LeetCode 3Sum Closest
- 3Sum Closest
- 3Sum Closest
- 3Sum Closest
- [LeetCode] 3Sum Closest
- tomcat JBoss 4.2 部署 去掉项目名称
- 压缩字符串
- 个人算法复习笔记1-二分查找
- C++中的explicit关键字
- java String字符串
- 3Sum Closest
- Zookeeper的安装和使用
- 一起看代码来玩玩QT之13 IO(one 基本)
- mac下查找设置$JAVA_HOME路径
- [LeetCode]1 两者之和
- java中静态代码块的用法 static用法详解
- CentOS 7.0 安装配置LAMP服务器方法(Apache+PHP+MariaDB)
- ModelDriven接口example
- 第一个html5页面(虽然是照着敲的)