LeetCode 16. 3Sum Closest
来源:互联网 发布:成都买车位划算 知乎 编辑:程序博客网 时间:2024/06/07 03:28
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).
题目大意:
给定一个数组nums和一个数字target。找出nums中三个数字的和最接近target的情况,并且返回这三个数字的和。
固定第一个数字,用两个指针一个从前面开始往后遍历,另一个从后面开始从前面开始遍历。
如果恰好有3个数的和等于target那么直接返回taeget结束操作即可。否则一只到遍历完成找出最接近target的结果。
题目代码:
class Solution {public: int threeSumClosest(vector<int>& nums, int target) { sort(nums.begin(), nums.end()); int l, r; long ans = INT_MAX; for(int i = 0; i < nums.size(); i++){ l = i+1; r = nums.size()-1; while(l < r){ int sum = nums[i] + nums[l] + nums[r]; if(sum == target){ return target; }else if(sum < target){ l++; }else{ r--; } if(abs(ans - target) > abs(target-sum)) ans = sum; } } return (int)ans; }};
阅读全文
1 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
- Python3.6 安装jpype1 遇到的一些坑以及最后安装jpype1成功的解决方法,不得不说
- BigDecimal和DecimalFormat
- 视频中的运动特征--Learning Motion Patterns in Videos
- call,apply,bind的区别
- 电脑上虚拟打印机如何将word转jpg
- LeetCode 16. 3Sum Closest
- autodesk backburne卸载问题
- sqlite基础一
- Dubbo与Zookeeper、Spring整合和使用
- ScrollView反弹效果 仿小米私密短信效果 android布局可滚动
- python遍历目录文件
- 微信实现分享转发功能
- iOS 直接改变.html后缀的链接所对应的html页面样式,并获取html的标题,图片地址,id,内容
- 第十四章——UINavigationController