3Sum Closest(离目标值最近的三数之和)
来源:互联网 发布:com域名不备案能解析吗 编辑:程序博客网 时间:2024/03/29 01:10
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). 解析:(1)对数组进行排序。(2)遍历数组中的每个元素。设置两个指针,start指向该元素后一个位置,last指向数组的末尾。(3)求出这三个数之和与目标值得差值,如果当前差值小于上一次的差值,则把当前差值更新为最小的差值。同时更新最后结果为三数之和。最后返回结果即可。int threeSumClosest(vector<int>& nums, int target){//最近距离int closestNum = INT_MAX;//三个数之和int res = 0;//当数组长度小于三时,返回最大整数if (nums.size() < 3)return closestNum;//对数组进行排序sort(nums.begin(), nums.end());//遍历数组for (int i = 0; i < nums.size() - 2; ++i){int start = i + 1;int last = nums.size() - 1;while (start < last){//当前三个数之和与目标值得差值int dis = nums[i] + nums[start] + nums[last] - target;//如果小于上一次的距离值,则更新最小距离和三个数之和if (abs(dis) < closestNum){closestNum = abs(dis);res = nums[i] + nums[start] + nums[last];}if (dis < 0){start++;}else if (dis > 0){last--;}else{return res;}}}return res;}
0 0
- 3Sum Closest(离目标值最近的三数之和)
- [LeetCode] 3Sum Closest 最近的三数之和 Python
- LeetCodet题解--16. 3Sum Closest(离给定值最近的三数之和)
- leetCode 16.3Sum Closest (离给定值最近的三数之和) 解题思路和方法
- leetcode解题之 16. 3Sum Closest Java版(结果离目标值最近三个数字和)
- 59.3Sum Closest-最接近的三数之和(中等题)
- 3Sum Closest 三数最接近
- [LeetCode]—3Sum Closest 求数组中三个数之和最接近给定target的组合
- 3sum 三数之和为0的简单实现
- Leetcode: 15. 3Sum 三数之和
- leetcode-3sum 三数之和
- [LeetCode] 3Sum 三数之和 Python
- 两数之和等于目标值
- leetcode 1 Two Sum(在无序数组中找两个数之和与目标值相等)
- Leetcode #16 3Sum Closest 找3数之和最接近 解题小节
- 3Sum Closest从数列中找到三个数之和最接近给定值
- Leetcode #15 3Sum 三数之和 解题小节
- LeetCode 15. 3Sum(三数之和)
- ios 性能优化之ImageView的那些事
- android studio强制关闭运行报错
- [从头学数学] 第198节 数学史选讲
- oracle表的备份
- 对集合类AbstractCollection借口toString方法的this关键字理解
- 3Sum Closest(离目标值最近的三数之和)
- 互联网服务端技术——如何学(上)
- 匿名函数
- ActiveMQ将消息持久化到数据库
- Java设计模式--策略模式
- PE 290【数位DP】
- DWR入门教程
- OSv—Optimizing the Operating System for Virtual Machines 5
- Python 进阶 —— warnings