python
1冒泡法
找出最小的k个数输出(超出时间限制)
class Solution:
def smallestK(self, arr: List[int], k: int) -> List[int]:
count = 0
for i in range(0,len(arr)):
min = i
for j in range(i,len(arr)):
if(arr[j]<arr[min]):
min = j
temp = arr[i]
arr[i] = arr[min]
arr[min] = temp
count += 1
if(count==k):
break
if(k==0):
return []
# print(arr)
return arr[0:k]
2.直接用python自带的函数
class Solution:
def smallestK(self, arr: List[int], k: int) -> List[int]:
arr.sort()
return arr[0:k]