剑指offer 40.最小的k个数。双百0ms

计数排序

class Solution {
    public int[] getLeastNumbers(int[] arr, int k) {
        if(k == 0 || arr.length == 0) return new int[0];
        int[] count = new int[10001];
        for(int num : arr) count[num]++;
        
        int[] result = new int[k];
        int index = 0;
        for(int i = 0; i < count.length; i++){
            while(count[i]-- > 0 && index < k) result[index++] = i;
            if(index == k) break;
        }
        return result;
    }
}
上一篇:C#重写继承方法,不能修改访问提示符。 cannot change access modifiers when overriding ‘public/protected..‘ inherited me


下一篇:(小白学java)Java 修饰符