1874. Kth Smallest Element in a Specific Array
Given an array with an unequal number of elements in each row, and the element of the same row is increasing. Find the kth smallest element in this specific array.
Example
Input:
[
[1, 5, 7, 9],
[3, 4],
[2, 7, 8]
]
k = 5
Output: 5
Notice
The number of elements per row ranges from [0, 500]
The total number of rows <=500
The values of all elements are [1, 1000000]
We guarantee that the number of elements in the array >= K
解法1:用最小堆
为什么用最小堆而不是用最大堆呢?用最大堆当然是可以的,但是时间复杂度就是O(nlogk)。用最小堆的复杂度是O(klogR)。这里R是matrix的有效行数,因为我们一开始就把每行的首元素放进去了。
注意这里跟LintCode 401: Kth Smallest Number in Sorted Matrix
LintCode 401. Kth Smallest Number in Sorted Matrix (堆经典好题!!!)_( the k?mn_纸上得来终觉浅 绝知此事要躬行的博客-优快云博客
那题不一样。那题是matrix里面没有空元素,并且行和列都排序,所以每次top一个元素,可以把右边元素和下面元素放进去。那题的时间复杂度是O(m+klogk),这里m是建堆复杂度。
struct Node {
int x;
int y;
int v;
Node(int _x = 0, int _y = 0, int _v = 0) : x(_x), y(_y), v(_v) {}
bool operator < (const Node & a) const {
return v > a.v;
}
};
class Solution {
public:
/**
* @param arr: an array of integers
* @param k: an integer
* @return: the Kth smallest element in a specific array
*/
int kthSmallest(vector<vector<int>> &arr, int k) {
int rowNum = arr.size();
priority_queue<Node> pq;
for (int i = 0; i < rowNum; ++i) {
if (arr[i].size() > 0) {
pq.push(Node(i, 0, arr[i][0]));
}
}
int count = 0;
while(!pq.empty()) {
Node top = pq.top();
pq.pop();
count++;
if (count == k) return top.v;
if (top.y < arr[top.x].size() - 1) {
pq.push(Node(top.x, top.y + 1, arr[top.x][top.y + 1]));
}
}
return -1;
}
};
此题和LintCode 104类似,只是LintCode 104用的是链表。
LintCode 104: Merge K Sorted Lists (经典题!)_纸上得来终觉浅 绝知此事要躬行的博客-优快云博客