632. Smallest Range
来源:互联网 发布:快递业务考试软件 编辑:程序博客网 时间:2024/05/22 18:21
632. Smallest Range
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个数组,问找到最小的一个范围[a,b],使得每一个数组当中至少有一个元素落入这个区间。
思路:
这道题将会用到贪心的思想,首先假设k个数组满足一下条件
[a01,a02,a03,a04……]
[a11,a12,a13,a14……]
……
[ak1,ak2,ak3,ak4……]
假设存在a01
vector<int> smallestRange(vector<vector<int>>& nums) { typedef vector<int>::iterator vi; struct comp { bool operator()(pair<vi, vi> p1, pair<vi, vi> p2) { return *p1.first > *p2.first; } }; int lo = INT_MAX, hi = INT_MIN; priority_queue<pair<vi, vi>, vector<pair<vi, vi>>, comp> pq; for (auto &row:nums){ lo = min(lo,row[0]); hi = max(hi,row[0]); pq.push({row.begin(),row.end()}); } vector<int> ans = {lo, hi}; while(true){ auto num =pq.top(); pq.pop(); num.first++; if(num.first==num.second){ break; } pq.push(num); lo = *pq.top().first; if(*num.first>hi) hi =*num.first; if(hi-lo<ans[1]-ans[0]){ ans[0]=lo; ans[1]=hi; } } return ans; }
- 632. Smallest Range
- leetcode 632. Smallest Range
- [LeetCode]632. Smallest Range
- 632. Smallest Range
- [leetcode]632. Smallest Range
- 【LeetCode】632. Smallest Range
- 632. Smallest Range
- leetcode题解 632. Smallest Range
- LeetCode Add to List 632. Smallest Range
- [LeetCode]632. Smallest Range 深入浅出讲解和代码示例
- leetcode 632. Smallest Range 典型的移动窗口做法
- [python]leetcode(632). Smallest Range
- Leetcode | Smallest Range(Hard)
- CareerCup Find the smallest range that includes at least one number from each of the k sorted lists.
- Range
- Range
- range
- range()
- Python学习----数字
- Oracle用户、表空间
- ubuntu 使用cron设置定时启动任务
- Python【map、reduce、filter】内置函数使用说明
- Python中list、tuple、str和dict之间的相互转换
- 632. Smallest Range
- Javascript函数表达式
- css属性
- 求大神指导
- kmp理解篇
- RecyclerView 的坑 1 Added View has RecyclerView as parent but view is not a real child. Unfiltered in
- shell命令之echo
- 将手机页面左右滚动固定
- secondarynamenode