leetcode 632. Smallest Range 典型的移动窗口做法
来源:互联网 发布:led胸牌软件 编辑:程序博客网 时间:2024/05/23 01:58
You have k lists of sorted integers in ascending order. Find the smallest range that includes at least one number from each of the k lists.
We define the range [a,b] is smaller than range [c,d] if b-a < d-c or a < c if b-a == d-c.
Example 1:
Input:[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]]
Output: [20,24]
Explanation:
List 1: [4, 10, 15, 24,26], 24 is in range [20,24].
List 2: [0, 9, 12, 20], 20 is in range [20,24].
List 3: [5, 18, 22, 30], 22 is in range [20,24].
Note:
The given list may contain duplicates, so ascending order means >= here.
1 <= k <= 3500
-105 <= value of elements <= 105.
本题题意很简单,虽然是分开的k个list,但是可以合并到一起,然后做排序,使用移动窗口去做即可
本质上和本题leetcode 76. Minimum Window Substring 双指针 + Map + 移动窗口 是一样的做法
代码如下:
#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>#include <functional>#include <bitset>#include <numeric>#include <cmath>#include <regex>using namespace std;class Solution {public: vector<int> smallestRange(vector<vector<int>>& nums) { vector<pair<int, int>> all; int kind = nums.size(); for (int i = 0; i < kind; i++) { for (int a : nums[i]) all.push_back(make_pair(a, i)); } sort(all.begin(), all.end()); map<int, int> mmp; vector<int> res = {INT_MAX,INT_MAX}; int left = 0, count = 0 , minDiff = INT_MAX; for (int right = 0; right < all.size(); right++) { mmp[all[right].second] += 1; if(mmp[all[right].second] == 1) count++; while (count == kind && left <= right) { int diff = all[right].first - all[left].first; if (diff < minDiff) { minDiff = diff; res = { all[left].first , all[right].first}; } else if (diff == minDiff && all[left].first < res[0]) res = { all[left].first , all[right].first }; mmp[all[left].second] -= 1; if (mmp[all[left].second] == 0) count--; left++; } } return res; }};
- leetcode 632. Smallest Range 典型的移动窗口做法
- leetcode 632. Smallest Range
- [LeetCode]632. Smallest Range
- [leetcode]632. Smallest Range
- 【LeetCode】632. Smallest Range
- leetcode题解 632. Smallest Range
- LeetCode Add to List 632. Smallest Range
- [python]leetcode(632). Smallest Range
- Leetcode | Smallest Range(Hard)
- 632. Smallest Range
- 632. Smallest Range
- 632. Smallest Range
- [LeetCode]632. Smallest Range 深入浅出讲解和代码示例
- leetcode 491. Increasing Subsequences 一个典型的深度优先遍历DFS的做法
- 移动广告的最佳做法
- 关于C#WINFORM登录窗口的做法
- 移动端多屏适配且保留高清图的做法
- 无标题窗口的移动
- C++内存管理 RAII
- iOS好使的各种文件文档、音乐、视频下载查看器有进度条
- 旅行悟出来的道理
- 贪吃蛇
- 【晒一晒】程序猿参加技术交流会议最喜欢什么小礼品?
- leetcode 632. Smallest Range 典型的移动窗口做法
- JVM系列四:生产环境参数实例及分析【生产环境实例增加中】
- RPC原理及RPC实例分析
- Linux -- centOS安装VIM命令
- pkg-config
- 单例设计模式
- I2C总线
- 打包用到的
- ubuntu 16.04 devstack 安装openstack pike