给定一个长度为 n 的可能有重复值的数组,找出其中不去重的最小的 k 个数。例如数组元素是4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4(任意顺序皆可)。
数据范围:,数组中每个数的大小
要求:空间复杂度 ,时间复杂度
[4,5,1,6,2,7,3,8],4
[1,2,3,4]
返回最小的4个数即可,返回[1,3,2,4]也可以
[1],0
[]
[0,1,2,1,2],3
[0,1,1]
#看了下k和tinput初始格式为int和list[元素为int] class Solution: def GetLeastNumbers_Solution(self, tinput, k): tinput.sort()#由于是int元素,不用转变直接sort str1 = tinput[0:k]#只要到第k个 return str1#返回数据
n = len(tinput) if k > n: return [] for i in range(n-1, 1, -1): for j in range(0, i): if tinput[j] > tinput[j+1]: tinput[j], tinput[j+1] = tinput[j+1], tinput[j] return tinput[:k]
# -*- coding:utf-8 -*- class Solution: def quickSort(self,nums): if not nums: return [] mid = nums[0] left = self.quickSort([x for x in nums[1:] if x<mid]) right = self.quickSort([x for x in nums[1:] if x>=mid]) return left+[mid]+right def GetLeastNumbers_Solution(self, tinput, k): # write code here # 先排序再取值 if k>len(tinput): return [] result = self.quickSort(tinput) return result[:k] # k次选择排序 # if k>len(tinput): # return [] # res = [] # for _ in range(k): # Min = tinput[0] # for num in tinput: # if num < Min: # Min = num # res.append(Min) # tinput.remove(Min) # return res
# -*- coding:utf-8 -*- class Solution: def GetLeastNumbers_Solution(self, tinput, k): # write code here if not tinput&nbs***bsp;k<0&nbs***bsp;k>len(tinput): return [] order=sorted(tinput) return order[:k]
# -*- coding:utf-8 -*- class Solution: def GetLeastNumbers_Solution(self, tinput, k): # write code here if k > len(tinput)&nbs***bsp;k==0: return [] else: tinput.sort() return tinput[:k]
# python一行,溜了溜了 # -*- coding:utf-8 -*- class Solution: def GetLeastNumbers_Solution(self, tinput, k): return [] if k>len(tinput) else sorted(tinput)[:k]
# -*- coding:utf-8 -*- class Solution: def fast_sort(self, arr): if len(arr) < 2: return arr else: pivot = arr[0] return self.fast_sort([x for x in arr[1:] if x <= pivot]) + [pivot] + self.fast_sort([x for x in arr[1:] if x > pivot]) def GetLeastNumbers_Solution(self, tinput, k): if k > len(tinput): return [] else: sorted_tinput = self.fast_sort(tinput) return sorted_tinput[:k] # write code here
# -*- coding:utf-8 -*- class Solution: def GetLeastNumbers_Solution(self, tinput, k): # write code here n=sorted(tinput) if k<=len(n): a=[i for i in n[0:] if i<=k] return a[:k] else: return []
# -*- coding:utf-8 -*- class Solution: def GetLeastNumbers_Solution(self, tinput, k): # write code here return [] if k > len(tinput) else sorted(tinput)[:k]
import heapq class Solution: def GetLeastNumbers_Solution(self, tinput, k): if tinput == [] or k > len(tinput): return [] return(heapq.nsmallest(k,tinput))