关于leetcode第K个最大元素的几种解法

  对于这一题我使用了最大堆,快速排序,归并排序几种解法来做这一题,速度最快的是归并排序

使用定值的最小堆每次更新数组最后剩下前k个最大元素,而且堆顶就是我们要的第K个元素。

堆排序:

import heapq
class Solution(object):
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        self.min_heap = []
        self.capacity = k
        self.nums = nums
        return self.get_k()
    def push(self, val):
        if len(self.min_heap) >= self.capacity:
            if self.min_heap[0]  < val:
                heapq.heapreplace(self.min_heap, val)
        else:
            heapq.heappush(self.min_heap, val)
    def get_k(self):
        for val in self.nums:
            self.push(val)
        return self.min_heap[0]

快速排序:

class Solution(object):
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        return nums[-k]

def fast_sort(self, nums):
        if len(nums)<2:
            return nums
        else:
            pivote = nums[0]
            l = [i for i in nums[1:] if i <=pivote]
            r = [i for i in nums[1:] if i > pivote]
            return self.fast_sort(l) + [pivote] + self.fast_sort(r)

时间是5052ms慢的吓人?

归并排序:

class Solution(object):
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        return self.merge_sort(nums)[-k]

 def merge_sort(self, nums):
        if len(nums) < 2:
            return nums
        else:
            mid = len(nums) // 2
            return self.sort_nums(self.merge_sort(nums[:mid]), self.merge_sort(nums[mid:]))

    def sort_nums(self, left, right):
        i, j = 0, 0
        s = []
        l_len, r_len = len(left), len(right)
        while i < l_len and j < r_len:
            if left[i] < right[j]:
                s.append(left[i])
                i += 1
            else:
                s.append(right[j])
                j += 1
        if i < l_len:
            s += left[i:]
        else:
            s += right[j:]
        return s

这个也是我自己实现的归并排序时间是 88ms

最后用Python自带的排序来做

class Solution(object):
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        nums.sort()
        return nums[-k]

时间是28ms听说Python排序底层也是用的归并排序只不过使用C语言实现的所以快很多

原文地址:https://www.cnblogs.com/python-zkp/p/10506724.html

时间: 2024-08-30 16:15:58

关于leetcode第K个最大元素的几种解法的相关文章

LeetCode算法题-Find the Difference(Java实现-五种解法)

这是悦乐书的第214次更新,第227篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第82题(顺位题号是389).给定两个字符串s和t,它们只包含小写字母.字符串t由随机混洗字符串s生成,然后在随机位置再添加一个字母.找到t中添加的字母.例如: 输入:s ="abcd", t ="abcde" 输出:'e' 说明:'e'是添加的字母. 本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Jav

[LeetCode] Kth Smallest Element in a Sorted Matrix 有序矩阵中第K小的元素

Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element. Example: matrix = [ [ 1, 5

LeetCode:数组中的第K个最大元素【215】

LeetCode:数组中的第K个最大元素[215] 题目描述 在未排序的数组中找到第 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 ≤ 数组的长度. 题目分析 我们主要来学习一个新的集合类型--优先队列.优先队列作用是保证每次取

[LeetCode]347. 前 K 个高频元素(堆)

题目 给定一个非空的整数数组,返回其中出现频率前?k?高的元素. 示例 1: 输入: nums = [1,1,1,2,2,3], k = 2 输出: [1,2] 示例 2: 输入: nums = [1], k = 1 输出: [1] 说明: 你可以假设给定的?k?总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数. 你的算法的时间复杂度必须优于 O(n log n) ,?n?是数组的大小. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problem

LeetCode | 0215. Kth Largest Element in an Array数组中的第K个最大元素【Python】

LeetCode 0215. Kth Largest Element in an Array数组中的第K个最大元素[Medium][Python][快排][堆] Problem LeetCode 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:

leetcode 二叉搜索树中第K小的元素 python

二叉搜索树中第K小的元素 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素. 说明:你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数. 示例 1: 输入: root = [3,1,4,null,2], k = 1 3 / 1 4   2 输出: 1 示例 2: 输入: root = [5,3,6,2,4,null,null,1], k = 3 5 / 3 6 / 2 4 / 1 输出: 3 进阶:如果二叉搜索树经常被修改(插入/删除操作)并且

LeetCode 215. 数组中的第K个最大元素(Kth Largest Element in an Array)

题目描述 在未排序的数组中找到第 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 ≤ 数组的长度. 解题思路 利用快速排序的思想,在进行排序过程中每次可以确定一个元素的最终位置,若此位置为第K个最大元素,则直接返回此索引,否则继续

Leetcode 215. 数组中的第K个最大元素 By Python

在未排序的数组中找到第 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 思路 一个sorted再直接返回第K个最大元素就好了 代码 class Solution(object): def findKthLargest(self, nums, k): """ :t

leetcode 230二叉搜索树中第k小的元素

通过stack进行中序遍历迭代,timeO(k),spaceO(1) /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ /** BST中序遍历是从小到大排列的因此对其进行中序遍历然后取第k个元素: **/