LeetCode刷题(C++)——3Sum Closest(Medium)
来源:互联网 发布:淘宝能买哪些虚拟产品 编辑:程序博客网 时间:2024/06/16 14: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)
思路:此题类似于3Sum这道题,在3Sum那道题的基础上稍微修改一下即可http://blog.csdn.net/yf_li123/article/details/71176581
class Solution {public: int threeSumClosest(vector<int>& nums, int target) { sort(nums.begin(), nums.end());int closest = INT_MAX;int ans = 0;for (int start = 0; start < nums.size();start++){int i = start + 1;int j = nums.size() - 1;while (i < j){int sum = nums[i] + nums[j] + nums[start];if (sum == target)return target;else if (sum < target){if ((target - sum) < closest){closest = target - sum;ans = sum;}while (i + 1 < nums.size() && nums[i] == nums[i + 1])i++;i++;}else{if ((sum - target) < closest){closest = sum - target;ans = sum;}while (j - 1 >= 0 && nums[j] == nums[j - 1])j--;j--;}}while (start + 1 < nums.size() && nums[start] == nums[start + 1])start++;}return ans; }};
0 0
- LeetCode刷题(C++)——3Sum Closest(Medium)
- LeetCode刷题(C++)——3Sum(Medium)
- 题解——Leetcode 16. 3Sum Closest 难度:Medium
- LeetCode刷题(C++)——4Sum(Medium)
- [LeetCode] 016. 3Sum Closest (Medium) (C++/Java/Python)
- [Leetcode 16, Medium] 3Sum Closest
- Leetcode 16. 3Sum Closest (Medium) (cpp)
- Leetcode 16. 3Sum Closest (Medium) (java)
- Leetcode: 16. 3Sum Closest(Week5, Medium)
- leetcode - 3Sum Closest (kSum Closest)
- 【leetcode】Array——3Sum Closest(16)
- LeetCode刷题(C++)——Path Sum II(Medium)
- LeetCode刷题(C++)——Minimum Path Sum(Medium)
- 【LeetCode算法练习(C++)】3Sum Closest
- LeetCode-16-3Sum Closest(证明/KSum)-Medium
- 16. 3Sum Closest Medium
- LeetCode——3Sum Closest
- LeetCode——3Sum Closest
- CentOS7 ping通 telnet不通
- 在html中显示本地图片
- POJ题型
- Python学习----DAY1
- tensorflow学习笔记(三):tensorflow 基础知识
- LeetCode刷题(C++)——3Sum Closest(Medium)
- 单例模式(Singleton mode)实战讲解
- Java语言中try-catch-finally中return解析以及引用类型和值类型区分
- C语言程序设计(6)
- 霍夫曼
- 一张图,教你用25种可视化工具如何完成
- JavaScript中本地对象、内置对象和宿主对象
- C语言程序设计(7)
- Spring IOC 透彻解析