繁体   English   中英

使用QuickSelect的第k个最小元素排序矩阵

[英]kth smallest element sorted matrix using QuickSelect

我知道之前已经有人问过这个问题,但是这个问题与我的特定代码有关。 我正在尝试做一个伪QuickSelect算法,将k与排序矩阵的子区间的中点进行比较。

我不断收到超时错误。

这是矩阵:

matrix = [
   [ 1,  5,  9],
   [10, 11, 13],
   [12, 13, 15]
],
k = 8

这是我的代码:

def kthSmallest(self, matrix, k):
    """
    :type matrix: List[List[int]]
    :type k: int
    :rtype: int
    """

    return self.matrixRecur(matrix, (0, 0), (len(matrix) - 1, len(matrix[0]) - 1), k)

def matrixRecur(self, splicedMatrix, left, right, k):
    start_row, start_col = left
    end_row, end_col = right
    mid_row = (start_row + end_row)/2
    mid_col = (start_col + end_col)/2

    i = start_row
    j = start_col
    lcount = 0
    while(not (i == mid_row and j == mid_col)):
        if j < len(splicedMatrix[0]):
            j += 1
        else:
            j = 0
            i += 1
        lcount += 1
    if k == lcount:
       return splicedMatrix[mid_row][mid_col]
    elif k < lcount:
        return self.matrixRecur(splicedMatrix, (start_row, start_col), (mid_row, mid_col), k)
    else:
        return self.matrixRecur(splicedMatrix, (mid_row, mid_col + 1), (end_row, end_col), k-lcount)

我将元组传递给matrixRecur ,其中包含间隔端点的(row, col) 因此,如果我想搜索整个矩阵,则传递(0, 0)(n, n) matrixRecur将查看一个子间隔,根据端点的行col编号确定中点,计算小于中点的元素数,并将其与k进行比较。 如果k小于小于中点的元素数( lcount ),则第k个最小元素在左间隔内,因为最多有lcount元素小于中点且k < lcount

我正在面试问题站点上运行此代码,该站点继续告诉我我的代码超时。 我不明白为什么。

您的上述方法无效。 由于矩阵是按行和按列进行排序的。 考虑如下矩阵

10, 20, 30, 40
15, 25, 35, 45
24, 29, 37, 48
32, 33, 39, 50

在这种情况下,您的方法将失败。 您正在遍历整个2D矩阵,因此超时。 最坏的情况是时间复杂度为O(mn) (m和n分别是行数和列数)。

您可以使用最小堆来解决此问题。

算法:

1. Build a min heap of first row elements. A heap entry also stores row number and column number.

2. for(int i=0;i<k;i++)
       Get minimum element (or root) from min heap.
       Find row number and column number of the minimum element.
       Replace root with the next element from same column and min-heapify the root.

3. Return the last extracted root.

时间复杂度: O(n + kLogn)

来源: 二维矩阵中最小的Kth

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM