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:

  1. The given list may contain duplicates, so ascending order means >= here.
  2. 1 <= k <= 3500
  3. -105 <= value of elements <= 105.
  4. For Java users, please note that the input type has been changed to List<List<Integer>>. And after you reset the code template, you'll see this point.

Approach #1: C++. [Using pointers]

class Solution {
public:
vector<int> smallestRange(vector<vector<int>>& nums) {
int size = nums.size();
vector<int> next(size, 0);
int minx = 0, miny = INT_MAX;
bool flag = true;
for (int i = 0; i < size && flag; ++i) {
for (int j = 0; j < nums[i].size() && flag; ++j) {
int min_i = 0, max_i = 0;
for (int k = 0; k < size; ++k) {
if (nums[min_i][next[min_i]] > nums[k][next[k]])
min_i = k;
if (nums[max_i][next[max_i]] < nums[k][next[k]])
max_i = k;
}
if (miny - minx > nums[max_i][next[max_i]] - nums[min_i][next[min_i]]) {
miny = nums[max_i][next[max_i]];
minx = nums[min_i][next[min_i]];
}
next[min_i]++;
if (next[min_i] == nums[min_i].size())
flag = false;
}
}
return {minx, miny};
}
};

Approach #2: Java. [Using pointers and priorityQueue]

class Solution {
public int[] smallestRange(List<List<Integer>> nums) {
int minx = 0, miny = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
int[] next = new int[nums.length];
boolean flag = true;
PriorityQueue<Integer> min_queue = new PriorityQueue<Integer>((i, j)->nums[i][next[i]] - nums[j][next[j]]);
for (int i = 0; i < nums.length; ++i) {
min_queue.offer(i);
max = Math.max(max, nums[i][0]);
}
for (int i = 0; i < nums.length && flag; ++i) {
for (int j = 0; j < nums[i].length && flag; ++j) {
int min_i = min_queue.poll();
if (miny - minx > max - nums[min_i][next[min_i]]) {
minx = nums[min_i][next[min_i]];
miny = max;
}
next[min_i]++;
if (next[min_i] == nums[min_i].length) {
flag = false;
break;
}
min_queue.offer(min_i);
max = Math.max(max, nums[min_i][next[min_i]]);
}
}
return new int[] {minx, miny};
}
}

I can't understand why it always compile error with this prompt: Line 10: error: cannot find symbol: method length().

This is the C++ version using priority_queue to solve this problem, may be it can understand easily.

#include <vector>
#include <queue>
#include <limits> using namespace std; struct Item {
int val;
int r;
int c; Item(int val, int r, int c): val(val), r(r), c(c) {
}
}; struct Comp {
bool operator() (const Item& it1, const Item& it2) {
return it2.val < it1.val;
}
}; class Solution {
public:
vector<int> smallestRange(vector<vector<int>>& nums) {
priority_queue<Item, vector<Item>, Comp> pq; int high = numeric_limits<int>::min();
int n = nums.size();
for (int i = 0; i < n; ++i) {
pq.push(Item(nums[i][0], i, 0));
high = max(high , nums[i][0]);
}
int low = pq.top().val; vector<int> res{low, high}; while (pq.size() == (size_t)n) {
auto it = pq.top();
pq.pop(); if ((size_t)it.c + 1 < nums[it.r].size()) {
pq.push(Item(nums[it.r][it.c + 1], it.r, it.c + 1));
high = max(high, nums[it.r][it.c + 1]);
low = pq.top().val;
if (high - low < res[1] - res[0]) {
res[0] = low;
res[1] = high;
}
}
} return res;
}
};

  

Approach #3: Python.

class Solution(object):
def smallestRange(self, A):
"""
:type nums: List[List[int]]
:rtype: List[int]
"""
pq = [(row[0], i, 0) for i, row in enumerate(A)]
heapq.heapify(pq) ans = -1e9, 1e9 right = max(row[0] for row in A)
while pq:
left, i, j = heapq.heappop(pq)
if right - left < ans[1] - ans[0]:
ans = left, right
if j + 1 == len(A[i]):
return ans
v = A[i][j+1]
right = max(right, v)
heapq.heappush(pq, (v, i, j+1))

  

Time Submitted Status Runtime Language
a few seconds ago Accepted 156 ms python
3 hours ago Accepted 1644 ms cpp

Analysis:

In the second approach this statement make me confused.

PriorityQueue < Integer > min_queue = new PriorityQueue < Integer > ((i, j) -> nums[i][next[i]] - nums[j][next[j]]);

may be it can sort automatically in the PriorityQueue function.

C++ ------> priorityqueue:

Priority Queue in C++ Standard Template Library (STL)

Priority queues are a type of container adapters, specifically designed such that the first element of the queue is the greatest of all elements in the queue and elements are in non decreasing order(hence we can see that each element of the queue has a priority{fixed order}).
 
The functions associated with priority queue are:
empty() – Returns whether the queue is empty
size() – Returns the size of the queue
top() – Returns a reference to the top most element of the queue
push(g) – Adds the element ‘g’ at the end of the queue
pop() – Deletes the first element of the queue

#include <iostream>
#include <queue> using namespace std; void showpq(priority_queue <int> gq)
{
priority_queue <int> g = gq;
while (!g.empty())
{
cout << '\t' << g.top();
g.pop();
}
cout << '\n';
} int main ()
{
priority_queue <int> gquiz;
gquiz.push(10);
gquiz.push(30);
gquiz.push(20);
gquiz.push(5);
gquiz.push(1); cout << "The priority queue gquiz is : ";
showpq(gquiz); cout << "\ngquiz.size() : " << gquiz.size();
cout << "\ngquiz.top() : " << gquiz.top(); cout << "\ngquiz.pop() : ";
gquiz.pop();
showpq(gquiz); return 0;
}

come from : https://www.geeksforgeeks.org/priority-queue-in-cpp-stl/

632. Smallest Range(priority_queue)的更多相关文章

  1. [LeetCode] 632. Smallest Range Covering Elements from K Lists 覆盖K个列表元素的最小区间

    You have k lists of sorted integers in ascending order. Find the smallest range that includes at lea ...

  2. [leetcode]632. Smallest Range最小范围

    You have k lists of sorted integers in ascending order. Find the smallest range that includes at lea ...

  3. 【LeetCode】632. Smallest Range 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/smallest ...

  4. [LeetCode] Smallest Range 最小的范围

    You have k lists of sorted integers in ascending order. Find the smallest range that includes at lea ...

  5. [Swift]LeetCode632. 最小区间 | Smallest Range

    You have k lists of sorted integers in ascending order. Find the smallest range that includes at lea ...

  6. 一道题目- Find the smallest range that includes at least one number from each of the k lists

    You have k lists of sorted integers. Find the smallest range that includes at least one number from ...

  7. [LeetCode] 910. Smallest Range II 最小区间之二

    Given an array A of integers, for each integer A[i] we need to choose either x = -K or x = K, and ad ...

  8. [LeetCode] 908. Smallest Range I 最小区间

    Given an array A of integers, for each integer A[i] we may choose any x with -K <= x <= K, and ...

  9. 【Leetcode_easy】908. Smallest Range I

    problem 908. Smallest Range I solution: class Solution { public: int smallestRangeI(vector<int> ...

随机推荐

  1. UVA 12130 - Summits(BFS+贪心)

    UVA 12130 - Summits 题目链接 题意:给定一个h * w的图,每一个位置有一个值.如今要求出这个图上的峰顶有多少个.峰顶是这样定义的.有一个d值,假设一个位置是峰顶.那么它不能走到不 ...

  2. Open Source Streaming Server--EasyDarwin

    Welcome to EasyDarwin Streaming Server, which is an open source Streaming Server Based On Appple's D ...

  3. Java类加载器( 死磕 4)

    [正文]Java类加载器(  CLassLoader ) 死磕 之4:  神秘的双亲委托机制 本小节目录 4.1. 每个类加载器都有一个parent父加载器 4.2. 类加载器之间的层次关系 4.3. ...

  4. vim实现代码缩进和可视区域的字符串替换

    今天2014年9月12号,实现了vim下的代码自动缩进和替换可视区域的字符串,之前一直在用vim这个强大的编辑器,它的强大只有用了的人才知道,现在把这两个很强大的功能展示出来,有个这两个功能,即使你写 ...

  5. Codeforces Round #178 (Div. 2) B. Shaass and Bookshelf —— DP

    题目链接:http://codeforces.com/contest/294/problem/B B. Shaass and Bookshelf time limit per test 1 secon ...

  6. Jmeter创建一个简单的http接口用例

    1.新建线程组 添加->Threads(Users)->线程组 线程组用来模拟用户进程. 2.添加http信息头管理器 添加->配置元件->http信息头管理器 Systemi ...

  7. python字典无序?有序?

    默认情况下Python的字典输出顺序是按照键的创建顺序. 字典的无序是指,不能人为重新排序.比如说你按键值1,2,3,4的顺序创建的字典,只能由解析器按创建顺序,还是1,2,3,4的输出.你无法控制它 ...

  8. codeforces B. Marathon 解题报告

    题目链接:http://codeforces.com/problemset/problem/404/B 题目意思:Valera 参加马拉松,马拉松的跑道是一个边长为a的正方形,要求Valera从起点( ...

  9. linux下mycat读写分离的配置

    为什么要配置读写分离,我想我就不需要再赘述了,那么在mycat下如何进行读写分离的配置,配置之后的实际效率又如何呢?我上午根据文档捣鼓和测试了一下,这里做一下记录: 最开始,我们还是要配置mysql本 ...

  10. 并不对劲的bzoj5322:loj2543:p4561:[JXOI2018]排序问题

    题目大意 \(T\)(\(T\leq10^5\))组询问 每次给出\(n,m,l,r\),和\(n\)个数\(a_1,a_2,...,a_n\),要找出\(m\)个可重复的在区间\([l,r]\)的数 ...