LeetCode题解 第十五周
来源:互联网 发布:仿淘宝app模板 编辑:程序博客网 时间:2024/06/01 09:32
1.3Sum Closest
https://leetcode.com/problems/3sum-closest/description/
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.
Example:
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).
Difficulty:Medium
code:
class Solution {public:int threeSumClosest(vector<int>& nums, int target1) {vector<vector<int>> res;int min = INT_MAX;int targetsum;sort(nums.begin(), nums.end());for (int i = 0; i < nums.size(); i++){int target = target1-nums[i];int front = i + 1;int back = nums.size() - 1;while (front < back){int sum = nums[i] + nums[front] + nums[back];if (abs(sum - target1) < min){min = abs(sum - target1);targetsum = sum;}if (nums[front] + nums[back] < target){front++;}else if (nums[front] + nums[back] > target){back--;}else{return target1;}}while (i + 1 < nums.size() && nums[i] == nums[i + 1]){i++;}}return targetsum;}};
阅读全文
0 0
- LeetCode题解 第十五周
- 第十五周leetcode题
- leetcode-第十五周
- 第十五周LeetCode
- 第十五周LeetCode
- 第十五周LeetCode
- 第十五周LeetCode
- 第十五周LeetCode
- 第十五周LeetCode
- Leetcode 算法习题 第十五周
- 第十五周LeetCode算法题两道
- LeetCode题解 第二周
- LeetCode题解 第三周
- LeetCode题解 第五周
- LeetCode题解 第六周
- LeetCode题解 第七周
- LeetCode题解 第八周
- LeetCode题解 第九周
- 反射之字段、方法、构造器的调用(二)
- 目前使用过的不经常使用的函数
- Redis 主从配置心得及其高可用方案
- git 初学使用
- python数据类型和变量
- LeetCode题解 第十五周
- Redis 内存淘汰机制
- 6.6
- Bash游戏 V2
- 第一章 Spring Cloud 服务提供者
- 最短路径:Dijkstral算法
- 个人总结
- Numpy教程
- JavaScript RegExp 对象