当前位置: 首页 > article >正文

机试刷题_寻找第K大【python】

题目:寻找第K大

描述
有一个整数数组,请你根据快速排序的思路,找出数组中第 k 大的数。

给定一个整数数组 a ,同时给定它的大小n和要找的 k ,请返回第 k 大的数(包括重复的元素,不用去重),保证答案存在。

from operator import le
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param a int整型一维数组 
# @param n int整型 
# @param K int整型 
# @return int整型
#
class Solution:
    def partition(self,nums,left,right):
        i = left
        j = right
        while i<j:
            while i<j and nums[j] >= nums[left]:
                j -= 1
            while i<j and nums[i] <= nums[left]:
                i += 1
            nums[i],nums[j] = nums[j],nums[i]
        nums[i],nums[left] = nums[left],nums[i]
        return i

    def quickSort(self,nums,left,right):
        # 子数组长度为 1 时终止递归
        if left >= right:
            return 
        # 哨兵划分
        base = self.partition(nums,left,right)

        self.quickSort(nums,left,base-1)
        self.quickSort(nums,base+1,right)

    def findKth(self , a: List[int], n: int, K: int) -> int:
        # 快排
        self.quickSort(a,0,n-1)
        print(a)
        return a[n-K]


http://www.kler.cn/a/547586.html

相关文章:

  • ElasticSearch基础和使用
  • UniApp 中制作一个横向滚动工具栏
  • 如何在 Mac 上解决 Qt Creator 安装后应用程序无法找到的问题
  • 技术速递|5 分钟用 GitHub Copilot Agent Mode 创建 Copilot Chat 应用
  • js考核第三题
  • 20250214 随笔 Elasticsearch(ES)索引数据 vs. 业务数据库冗余双写
  • 智能AI之隐私安全,尤其是医疗
  • Python - 构造函数、继承与重载
  • firefox的升级
  • 【PyQt】PyQt复选框与单选框
  • 【Linux网络编程】应用层协议HTTP(请求方法,状态码,重定向,cookie,session)
  • 类与对象C++详解(中)-----构造函数与析构函数
  • Unity CommandBuffer绘制粒子系统网格显示
  • 《Mycat核心技术》第14章:实现ER分片
  • VSCode配合cline实现自动编程
  • 5分钟掌握LM Studio本地部署DeepSeek R1
  • Spark 性能优化(四):Cache
  • 2025 (ISC)²CCSP 回忆录
  • 简述 tsconfig.json 中 rootDir 和 include 之间的关系
  • 设计模式——职责链模式