输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
1 import heapq 2 # -*- coding:utf-8 -*- 3 class Solution: 4 def GetLeastNumbers_Solution(self, tinput, k): 5 n = len(tinput) 6 if k > n: 7 return [] 8 result = heapq.nsmallest(k, tinput) 9 return result 10 # write code here
Java版代码,leetcode地址:
1 class Solution { 2 public int[] getLeastNumbers(int[] arr, int k) { 3 Arrays.sort(arr); 4 int[] result = Arrays.copyOfRange(arr, 0, k); 5 return result; 6 } 7 }