3Sum Closest
来源:互联网 发布:淘宝门票类商品退款 编辑:程序博客网 时间:2024/06/03 23:40
每日算法——leetcode系列
问题 3Sum Closest
Difficulty: Medium
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).
class Solution {public: int threeSumClosest(vector<int>& nums, int target) { }};
翻译
三数和
难度系数:中等
给定一个有n个整数的数组S, 找出数组S中三个数的和最接近一个指定的数。 返回这三个数的和。 你可以假定每个输入都有一个结果。
思路
思路跟3Sum很像, 不同的就是不用去重复, 要记录三和最接近target的和值。
代码
class Solution {public: int threeSumClosest(vector<int>& nums, int target) { int result = 0; int minDiff = INT32_MAX; // 排序 sort(nums.begin(), nums.end()); int n = static_cast<int>(nums.size()); for (int i = 0; i < n - 2; ++i) { int j = i + 1; int k = n - 1; while (j < k) { int sum = nums[i] + nums[j] + nums[k]; int diff = abs(sum - target); // 记录三和最接近target的和值 if (minDiff > diff){ result = sum; minDiff = diff; } else if (sum < target){ j++; } else if (sum > target){ k--; } else{ return result; } } } return result; }};
0 0
- 3 Sum & 3 Sum Closest
- 【Leetcode】3Sum Closest (Sum)
- LeetCode: 3 Sum Closest
- 3Sum Closest
- leetcode - 3 sum closest
- leetcode 3Sum Closest
- LeetCode: 3Sum Closest
- [Leetcode]3Sum Closest
- Leetcode: 3SUM Closest
- LeetCode 3Sum Closest
- [Leetcode] 3Sum Closest
- leetcode002:3sum closest
- LeetCode : 3Sum Closest
- LeetCode 3Sum Closest
- 3Sum Closest
- 3Sum Closest
- 3Sum Closest
- [LeetCode] 3Sum Closest
- Ubuntu10下安装JAVA JDK
- Ubuntu10下MySQL搭建Amoeba_分片升级版
- 151224总结
- Ubuntu10下MySQL搭建Amoeba_分片
- 5.Linux操作系统及常用命令
- 3Sum Closest
- SpriteBuilder中使用GUI界面快速搭建RPG游戏中的地图名显示动画
- 2016太郭文军原网络营销师讲解微博和微信的区别?
- 从测试角度看职业生涯
- 如何在windows下的Python开发工具IDLE里安装其他模块
- Java中的线程池——3种常用的ThreadPoolExecutor
- XAF信息系统快速框架介绍
- XAF应用开发教程(一) 创建项目
- 点扩散函数3D曲面绘图方法