劍指offer面試題40 最小的k個數

2021-09-29 08:35:35 字數 1921 閱讀 3817

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

方法一:快速排序,o(n),修改原陣列

要注意和原始快排的區別, 當不滿足start < end時,需要返回end,而不是直接返回

方法二:堆排序(k個元素的最大堆),o(nlogk),適合海量資料,如果待插入的值比當前已有的最大值小,則用這個數替換當前已有的最大值,如果待插入的值比當前已有的最大值大,那麼這個數不可能是最小的整數之一

方法一:

# -*- coding:utf-8 -*-

class solution:

def partition(self, start, end, nums):

if start < end:

i = start

j = end + 1

k = nums[start]

while i < j:

i += 1

while i < end and nums[i] < k:

i += 1

j -= 1

while j > start and nums[j] > k:

j -= 1

if i < j:

nums[i], nums[j] = nums[j], nums[i]

nums[start], nums[j] = nums[j], nums[start]

return j

# 注意和原始快排的區別

else:

return end

def getleastnumbers_solution(self, tinput, k):

# write code here

if k == 0 or len(tinput) == 0:

return

if k > len(tinput):

return

start=0

end=len(tinput)-1

index = self.partition(start, end, tinput)

while true:

if index == k - 1:

print tinput[:k]

res=tinput[:k]

res.sort()

return res

elif index < k - 1:

start = index + 1

index=self.partition(start, end, tinput)

else:

end = index - 1

index=self.partition(start, end, tinput)

方法二:

import heapq

class solution:

def getleastnumbers_solution(self, tinput, k):

# write code here

if k == 0 or len(tinput) == 0:

return

if k > len(tinput):

return

heap=[-tinput[i] for i in range(k)]

heapq.heapify(heap)

for i in range(k,len(tinput)):

if tinput[i]<-heap[0]:

heapq.heapreplace(heap,-tinput[i])

heap = [-heap[i] for i in range(k)]

heap.sort()

return heap

劍指offer 面試題40 最小的K個數

面試題 劍指offer 題目解答 輸入n個整數,找出其中最小的k個數。例如輸入4,5,1,6,2,7,3,8這8個數字,則最小的4個數字是1,2,3,4,坑點 輸入n個整數,找出其中最小的k個數 在這裡我們很容易在主觀上預設n k,從而在討論k的不合法性時,忘記了k n的情況,實際上當 k n 或者...

劍指offer面試題7

面試題7 用兩個棧實現佇列 using namespace std template class cqueue 預備知識 佇列 佇列也是一種常見的資料結構 特點是先進先出 fifo 在stl中有stack和queue兩個容器 template class stack 成員函式 empty size ...

劍指offer面試題11

面試題1 數值的整數的次方 題目 實現函式double power double base,int exponent 求base的 exponent次方。不得使用庫函式,同時不需要考慮大數問題。思路 首先應該明確指數的可能取值 正整數,0,負整數 另外還需要考慮底數是0的情形。對於負整指數,我們可以...