前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【python刷题】寻找数组中第K大/小的数

【python刷题】寻找数组中第K大/小的数

作者头像
西西嘛呦
发布2021-02-22 11:34:03
1.4K0
发布2021-02-22 11:34:03
举报
文章被收录于专栏:数据分析与挖掘

借鉴快速排序的思想

快速排序代码

代码语言:javascript
复制
def quicksort(nums):
    l = 0
    r = len(nums)-1
    _quicksort(nums, l, r)


def _quicksort(nums, left, right):
    l = left
    r = right
    if l < r:
        tmp = nums[l]
        while l < r:
            while l < r and tmp <= nums[r]:
                r -= 1
            nums[l], nums[r] = nums[r], nums[l]
            while l < r and tmp > nums[l]:
                l += 1
            nums[l], nums[r] = nums[r], nums[l]
        _quicksort(nums, left, l)
        _quicksort(nums, l+1, right)
nums = [6,2,4,1,2,3,5,2,7]
quicksort(nums)
print(nums)

借鉴快速排序思想

代码语言:javascript
复制
def findKthLargest(numbers, start, end, k):
  if k < 0 or numbers == [] or start < 0 or end >= len(numbers) or k > end:
    return None
  low = start
  high = end
  key = numbers[start]
  while low < high:
    while low < high and numbers[high] >= key:
      high -= 1
    numbers[low] = numbers[high]
    while low < high and numbers[low] <= key:
      low += 1
    numbers[high] = numbers[low]
  numbers[low] = key
  if low < k:
    return partitionOfK(numbers, low+ 1, end, k)
  elif low > k:
    return partitionOfK(numbers, start, low- 1, k)
  else:
    return numbers[low]
numbers = [3,5,6,7,2,-1,9,3]
print(sorted(numbers))
print(partitionOfK(numbers, 0, len(numbers) - 1, 5))
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-02-04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 借鉴快速排序的思想
    • 快速排序代码
      • 借鉴快速排序思想
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档