【LeetCode】3Sum Closest
来源:互联网 发布:qq截图软件绿色版 编辑:程序博客网 时间:2024/06/08 01:36
算法小白,最近刷LeetCode。希望能够结合自己的思考和别人优秀的代码,对题目和解法进行更加清晰详细的解释,供大家参考^_^
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,给出O(n^2)的方法。
class Solution {public: int threeSumClosest(vector<int>& nums, int target) { int res = nums[0] + nums[1] + nums[2]; int len = nums.size(); sort(nums.begin(), nums.end()); for (int i = 0; i < len; ++i){ int beg = i + 1, end = len - 1; while (beg < end){ int sum = nums[i] + nums[beg] + nums[end]; // 计算三个数的和 res = abs(sum - target) < abs(res - target) ? sum : res; // 更新res if (sum > target) --end; else if (sum < target) ++beg; else return res; // 相等,直接返回 } } return res; }};
0 0
- LeetCode: 3 Sum Closest
- leetcode - 3 sum closest
- leetcode 3Sum Closest
- LeetCode: 3Sum Closest
- [Leetcode]3Sum Closest
- Leetcode: 3SUM Closest
- LeetCode 3Sum Closest
- [Leetcode] 3Sum Closest
- LeetCode : 3Sum Closest
- LeetCode 3Sum Closest
- [LeetCode] 3Sum Closest
- 【leetcode】3Sum Closest
- [LeetCode]3Sum Closest
- LeetCode-3Sum Closest
- LeetCode:3Sum Closest
- LeetCode | 3Sum Closest
- 【leetcode】3Sum Closest
- Leetcode: 3Sum Closest
- 安卓设置状态栏颜色
- struts2上传文件的时候,action里面获取上传文件的文件名和类型的原理是什么?
- C++11 标准新特性: 右值引用与转移语义
- Windows 系统错误193 0xc1
- 第五章--字符串的创建方式、连接方式、获取字符串信息的方式、常用操作、格式化、正则表达式、字符串生成器的用法
- 【LeetCode】3Sum Closest
- 设计模式的六大原则
- Nginx 配置项介绍
- Mac下载并编译Android源码
- 「 标准 」NTSC、PAL、SECAM 三大制式简介
- javascript 模板引擎artTemplate
- windows下配置JAVA虚拟机以及环境变量
- qt5 打开中文路径的图片失败
- 计算机系统漫游·一