算法刷题Day1

BM47 寻找第k大

第一天就随便记录吧,万事开头难,我好不容易开的头,就别难为自己,去追求高质量了。嘿嘿嘿
题目 传送门

解题思路一:维护一个大小为k的最小堆。最后返回堆顶元素。

代码:

python 复制代码
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param a int整型一维数组
# @param n int整型
# @param K int整型
# @return int整型
#
from heapq import heappushpop
from typing import List


#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param a int整型一维数组
# @param n int整型
# @param K int整型
# @return int整型
#
from heapq import heappushpop
from typing import List


class Solution:
    def findKth(self , a: List[int], n: int, K: int) -> int:
        # write code here
        # 维护一个大小为k的最小堆。最后返回堆顶元素
        import heapq
        heap = []
        # 将前k个数压进数组
        for i in range(K):
            heapq.heappush(heap, a[i])
        print(f"heap = {heap}")
        for i in range(K,n):
            # 取堆顶元素,如果堆顶元素小,poppush,如果堆顶元素一样,push。如果堆顶元素大,pass
            heap_top = heap[0]
            print(f"{a[i], heap_top}")
            if a[i] > heap_top:
                heapq.heappop(heap)
                heapq.heappush(heap,a[i])
            elif a[i] == heap_top:
                heapq.heappush(heap,a[i])
            else:
                pass
        print(heap)
        return heap[-K]
so = Solution()
a,n,K = [10,10,9,9,8,7,5,6,4,3,4,2],12,3
print(so.findKth(a,n,K)) 

解题思路二:二分查找,这个思路很值得学习
思路二 原帖传送门

等我实现实现

相关推荐
meilindehuzi_a18 分钟前
Python 基础语法(1):常量、变量、类型、输入输出与运算符
开发语言·python
Zane199431 分钟前
调用了 async 函数却没执行?一文讲透协程、event loop 与 await
后端·python
OPEN-F34 分钟前
Python进阶教程:装饰器与生成器深入
开发语言·python
zhipujiaoyu39 分钟前
2026年大数据专科何去何从?就业前景、发展趋势全揭秘!
大数据·python
l1258651 小时前
# RAG噪声知识库治理:一致性与可信度的四层防线设计
数据库·人工智能·python·自然语言处理·langchain
zoujiahui_20181 小时前
别再只写 np.random.seed() 了:default_rng 与 np.random、random 到底差在哪?
python
Patrick在香港1 小时前
Claude Agent 进阶:4 种工具调用编排模式,让 0820 那 13 个 endpoint 并行起来
python·ai·ai编程
happyprince1 小时前
01-整体观-Codex全貌解读(源码)
算法·ai编程
俊基科技2 小时前
别自己写算法了,让这颗37.5毫米的模组替你“闭嘴干活”
神经网络·算法·硬件开发·ai降噪·语音模块·回音消除
qq_513728042 小时前
StaleElementReferenceException(陈旧元素引用异常)
python