Skip to content

17.14. Smallest K

Description

Design an algorithm to find the smallest K numbers in an array.

Example:


Input:  arr = [1,3,5,7,2,4,6,8], k = 4

Output:  [1,2,3,4]

Note:

  • 0 <= len(arr) <= 100000
  • 0 <= k <= min(100000, len(arr))

Solutions

Solution 1

1
2
3
class Solution:
    def smallestK(self, arr: List[int], k: int) -> List[int]:
        return sorted(arr)[:k]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
    public int[] smallestK(int[] arr, int k) {
        Arrays.sort(arr);
        int[] ans = new int[k];
        for (