LeetCode题解:3sum closest
来源:互联网 发布:mac的办公软件 编辑:程序博客网 时间:2024/04/30 16:54
3Sum Closest
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).
思路:
类似3Sum,只不过每次求和的时候都和已知的最接近的值比对一下,随时更新已经找到的最优解。
题解:
class Solution {public: int threeSumClosest(vector<int> &num, int target) { int closest = numeric_limits<int>::max(); int sum = 0; sort(begin(num), end(num)); for(size_t i = 0; i < num.size() - 2; ++i) { int j = i + 1; int k = num.size() - 1; int expectation = target - num[i]; while(j < k) { int diff = expectation - num[j] - num[k]; if (abs(closest) > abs(diff)) { closest = diff; sum = target - diff; } if (diff < 0) k--; else if (diff > 0) j++; else return target; } } return sum; }};
- LeetCode题解:3sum closest
- LeetCode题解:3Sum Closest
- [LeetCode]3Sum Closest题解
- Leetcode题解-3Sum&3Sum Closest
- leetcode 题解 || 3Sum Closest 问题
- LeetCode 题解(76): 3Sum Closest
- LeetCode题解——3Sum Closest
- LeetCode题解-16-3Sum Closest
- 16. 3Sum Closest LeetCode题解
- leetcode题解-16. 3Sum Closest
- 3Sum Closest题解
- 题解:3Sum Closest
- 【LeetCode】3Sum,3Sum Closest 题解报告
- leetcode题解-15. 3Sum && 16. 3Sum Closest
- 《LeetBook》leetcode题解(16):3Sum Closest [M]
- 3Sum Closest - leetcode 16号题目个人题解
- 题解——Leetcode 16. 3Sum Closest 难度:Medium
- LeetCode: 3 Sum Closest
- py文件编译为pyc
- 详细介绍Java内存泄露原因
- POJ_1753
- 去掉字符串中的数字
- Java内存泄露小例子
- LeetCode题解:3sum closest
- 用位运算生成分形
- 手势、画图、截图
- Debian 7 下搭建 IPSEC + L2TP VPN 服务器
- Java中的Set,List,Map的区别
- Linux内核访问I/O资源的方法:动态映射(ioremap)和静态映射(map_desc)
- android手机连不上电脑总结
- 堆、栈、BSS、Data、code区、静态存储区、文字常量区
- 关于操作数关系