设计一个算法,找出数组中最小的k个数。以任意顺序返回这k个数均可。
示例:
输入: arr = [1,3,5,7,2,4,6,8], k = 4
输出: [1,2,3,4]
提示:
- 0 <= len(arr) <= 100000
- 0 <= k <= min(100000, len(arr))
Python 解答:
1.库函数
import heapq
class Solution:
def smallestK(self, arr: List[int], k: int) -> List[int]:
return heapq.nsmallest(k, arr)
2.排序
class Solution:
def smallestK(self, arr: List[int], k: int) -> List[int]:
return sorted(arr)[:k]
3.分治
import heapq
class Solution:
def smallestK(self, arr: List[int], k: int) -> List[int]:
def quickK(arr, l, r, k):
if l < r:
i, j = l, r
primer = arr[l]
while i < j:
while i < j and arr[j] > primer:
j -= 1
arr[i] = arr[j]
while i < j and arr[i] <= primer:
i += 1
arr[j] = arr[i]
arr[i] = primer
if i == k-1:
return
elif i > k-1:
quickK(arr, l, i-1, k)
else:
quickK(arr, i+1, r, k)
quickK(arr, 0, len(arr)-1, k)
return arr[:k]
留言