【LeetCode】215. Kth Largest Element in an Array

拜拜、爱过 提交于 2020-04-17 19:53:03

我的个人微信公众号:Microstrong

微信公众号ID:MicrostrongAI

微信公众号介绍:Microstrong(小强)同学主要研究机器学习、深度学习、计算机视觉、智能对话系统相关内容,分享在学习过程中的读书笔记!期待您的关注,欢迎一起学习交流进步!

知乎主页:https://www.zhihu.com/people/MicrostrongAI/activities

Github:https://github.com/Microstrong0305

个人博客:https://blog.csdn.net/program_developer

215. Kth Largest Element in an Array

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Example 1:

Input: [3,2,1,5,6,4] and k = 2
Output: 5

Example 2:

Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4

Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.

解题思路:

(1)堆排序

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        """
        :param nums: List[int] 待排序列表
        :param k: int 第k大数值
        :return: int 返回值
        """
        length = len(nums)
        # 构建大顶堆
        for i in range(length // 2 - 1, -1, -1):
            self.adjustHeap(nums, i, length)

        count = 0
        for j in range(length - 1, -1, -1):
            count += 1
            if count == k:
                return nums[0]
            self.swap(nums, 0, j)
            length -= 1
            self.adjustHeap(nums, 0, length)

    def adjustHeap(self, nums, i, length):
        """
        :param nums: 待排序数组
        :param i: 指定以i为根结点排序
        :param length: 待排序数组长度
        :return:
        """
        while True:
            leftChild = i * 2 + 1
            if leftChild >= length:
                return
            if leftChild + 1 < length and nums[leftChild + 1] > nums[leftChild]:
                leftChild += 1
            if nums[leftChild] > nums[i]:
                self.swap(nums, i, leftChild)
                i = leftChild
            else:
                return

    def swap(self, nums, i, j):
        temp = nums[i]
        nums[i] = nums[j]
        nums[j] = temp
   

 

发布了301 篇原创文章 · 获赞 1099 · 访问量 131万+
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!