剑指offer 40.最小的 K 个数 python代码
生活随笔
收集整理的這篇文章主要介紹了
剑指offer 40.最小的 K 个数 python代码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
尋找數組中的最小的k個數,也叫topk問題。
??途W測試地址
注意:
??途W的提交需要將最終的結果排序
思路
快速排序的 partition() 方法,會返回一個整數 j 使得 a[l…j-1] 小于等于 a[j],且 a[j+1…h] 大于等于 a[j],此時 a[j] 就是數組的第 j 大元素。可以利用這個特性找出數組的第 K 個元素,這種找第 K 個元素的算法稱為快速選擇算法。
代碼
# -*- coding: utf-8 -*-# !/usr/bin/env python# Time: 2018/5/13 15:39# Author: sty# File: 40. GetLeastNumbers.pyclass Solution:"""最小的 K 個數practice:https://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf?tpId=13&tqId=11182&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking"""def find_kth_smallest(self, nums, k):l, h = 0, len(nums) - 1while l < h:j = self.partition(nums, l, h)if j == k:breakif j > k:h = j - 1else:l = j + 1return nums[k]def partition(self, nums, low, high):parti = nums[low]while low < high:while low < high and nums[high] >= parti:high -= 1nums[low] = nums[high]while low < high and nums[low] <= parti:low += 1nums[high] = nums[low]nums[low] = partireturn lowdef GetLeastNumbers_Solution(self, tinput, k):res = []if k > len(tinput) or k <= 0:return resself.find_kth_smallest(tinput, k - 1)for i in range(k):res.append(tinput[i])return sorted(res)# a = Solution()
# print(a.GetLeastNumbers_Solution([4,5,1,6,2,7,3,8], 4))
總結
以上是生活随笔為你收集整理的剑指offer 40.最小的 K 个数 python代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 30. Substri
- 下一篇: 3分钟4 步快速带你在win10电脑装上