题目链接:​点击打开链接​

题目大意:

解题思路:

相关企业

  • 字节跳动

AC 代码

  • Java
class Solution {

public int[] getLeastNumbers(int[] arr, int k) {

int min = arr[0], max = arr[0];
for (int i = 1; i < arr.length; i++) {
int val = arr[i];
if (val < min) min = val;
if (val > max) max = val;
}

int size = max - min + 1;
int[] tmp = new int[size];
for (int i = 0; i < arr.length; i++) {
tmp[arr[i] - min]++;
}

arr = new int[k];
for (int i = 0, j = 0; i < tmp.length; i++) {
while (tmp[i] > 0 && j < k) {
arr[j++] = i + min;
tmp[i]--;
}
if (j >= k) {
break;
}
}

return arr;
}
}