使用 quick select 获取第 k 个最大的元素

Getting the kth largest elemtent with quick select

我写了一些 python 代码来获取未排序数组中的第 K 个最小元素。我想获得帮助以反转函数以获得第 K 个最大元素。我知道 Whosebug 上还有其他问题可以回答这个问题,但老实说,我不在这里是因为我希望我的问题得到解答。我来这里是因为我想要模式,如何思考这样的问题,这样下次我看到这样的问题时我就能回答。所以请给我解释清楚,帮助我真正明白该怎么做,这样我以后才能做类似的问题。

from typing import List


def partition(array: List[int], lowerbound: int, upperbound: int) -> int:
    """
    Partitions the array so that lower items are to the left of the pivot and bigger items are to the right.
    """
    pivot = array[upperbound]
    index_1 = lowerbound - 1

    for index_2 in range(lowerbound, upperbound):  # we loop from lowerbound and stop just before the pivot.
        if array[index_2] < pivot:  # if the value at index 2 is less than the pivot.
            index_1 += 1
            array[index_1], array[index_2] = array[index_2], array[index_1]  # swap index one and two
    array[index_1 + 1], array[upperbound] = array[upperbound], array[index_1 + 1]
    return index_1 + 1  # return the pivot(basically it's index)


def quick_select(array: List[int], lowerbound: int, upperbound: int, item_index: int) -> int:
    """
    Performs the quick select algorithm.
    """
    if lowerbound >= upperbound:
        return array[lowerbound]

    pivot_index = partition(array, lowerbound, upperbound)
    if pivot_index == item_index:
        return array[item_index]

    if pivot_index > item_index:
        return quick_select(array, lowerbound, pivot_index - 1, item_index)
    else:
        return quick_select(array, pivot_index + 1, upperbound, item_index)
    ```


至少有两种方式:

  • 第K大第(N+1-K)小,算法都不用重写

  • 在给定的代码中,只要有元素比较,就翻转它的方向(将 > 转为 <,>= 为 <= 等等)。注意:我的意思是仅 元素比较 .


另一种选择是更改数组中所有元素的符号,寻找最小的元素并恢复符号。

我不推荐这种方法,除非符号的改变是虚拟完成的,即假设在涉及元素的语句中。例如。 a > b 改写为 -a > -b,也就是 a < b,这又把我们带回到第二种方法。

获得第 K 个最大的代码是必不可少的,您只需以另一种方式进行索引。

完全未经测试的代码

def KthLargest(array: List[int], item_index: int)
  return quick_select(array, 0, len(List), len(list)-item_index) # off-by-one?