美文网首页
LeetCode 第 215 题:在未排序的数组中找到第 k 个

LeetCode 第 215 题:在未排序的数组中找到第 k 个

作者: 李威威 | 来源:发表于2019-05-29 23:25 被阅读0次

传送门:215. 数组中的第K个最大元素

在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。

示例 1:

输入: [3,2,1,5,6,4] 和 k = 2
输出: 5

示例 2:

输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4

说明:

你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。

这道题应该说是无比重要的高频考题,是一定要掌握的,两种思路分别使用了很基础的数据结构(优先队列)和算法(partition)。

解法1:使用快速排序 partition 的思路

Python 代码:

class Solution:

    # 数组中的第 K 个最大元素
    # 数组中第 k 大的元素,它的索引是 len(nums) - k
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """

        left = 0
        right = len(nums) - 1

        while True:
            index = self.__partition(nums, left, right)
            if index == len(nums) - k:
                return nums[index]
            if index > len(nums) - k:
                right = index - 1
            else:
                left = index + 1

    def __partition(self, nums, left, right):
        """
        partition 是必须要会的子步骤,一定要非常熟练
        典型的例子就是:[3,7,8,1,2,4]
        遇到比第一个元素大的或等于的,就放过,遇到小的,就交换
        在 [left,right] 这个区间执行 partition
        :param nums:
        :param left:
        :param right:
        :return:
        """
        pivot = nums[left]
        k = left
        for index in range(left + 1, right + 1):
            if nums[index] < pivot:
                k += 1
                nums[k], nums[index] = nums[index], nums[k]
        nums[left], nums[k] = nums[k], nums[left]
        return k


if __name__ == '__main__':
    nums = [3, 7, 8, 1, 2, 4]
    solution = Solution()
    result = solution.findKthLargest(nums, 2)
    print(result)

解法2:使用优先队列

参考了:https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/167837/Python-or-tm

Python 代码:

import heapq

class Solution(object):
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        L = []
        for index in range(k):
            # 默认是最小堆
            heapq.heappush(L, nums[index])
        for index in range(k, len(nums)):
            top = L[0]
            if nums[index] > top:
                # 看一看堆顶的元素,只要比堆顶元素大,就替换堆顶元素
                heapq.heapreplace(L, nums[index])
        # 最后堆顶中的元素就是堆中最小的,整个数组中的第 k 大元素
        return L[0]


if __name__ == '__main__':
    nums = [3, 7, 8, 1, 2, 4]
    solution = Solution()
    result = solution.findKthLargest(nums, 2)
    print(result)

(本节完)

相关文章

网友评论

      本文标题:LeetCode 第 215 题:在未排序的数组中找到第 k 个

      本文链接:https://www.haomeiwen.com/subject/mmlptctx.html