劍指offer 面試40題


面試40題:

題目:最小的k個數

題:輸入n個整數,找出其中最小的K個數。例如輸入4,5,1,6,2,7,3,8這8個數字,則最小的4個數字是1,2,3,4,。

解題代碼一:

# -*- coding:utf-8 -*-
class Solution:
    def GetLeastNumbers_Solution(self, tinput, k):
        # write code here
        #此方法時間復雜度為O(nlogn)
        if k >len(tinput):
            return []
        tinput.sort()
        return tinput[:k]

解題代碼二:

# -*- coding:utf-8 -*-
class Solution:
    def GetLeastNumbers_Solution(self, tinput, k):
        # write code here
        import heapq
        #此方法時間復雜度為O(nlogk)
        if k >len(tinput):
            return []
        return heapq.nsmallest(k,tinput)

解題代碼三:另:自己實現快速排序

# -*- coding:utf-8 -*-
class Solution:
    def GetLeastNumbers_Solution(self, tinput, k):
        # write code here
        #此方法時間復雜度為O(nlogn)
        if k >len(tinput) or not tinput:
            return []
        #tinput.sort()
        #實現一個快速排序
        def quick_sort(array):
            if not array:
                return []
            pivot=array[0]
            left=quick_sort([x for x in array[1:] if x<pivot])
            right=quick_sort([x for x in array[1:] if x>=pivot])
            return left+[pivot]+right
        
        return quick_sort(tinput)[:k]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM