解答
package leetcode.editor.cn;
import java.util.Comparator;
import java.util.PriorityQueue;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int[] smallestK(int[] arr, int k) {
if (arr == null || arr.length == 0 || k <= 0) {
return new int[]{};
}
PriorityQueue<Integer> queue = new PriorityQueue<>(arr.length, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
for (int i = 0; i < arr.length; ++i) {
queue.add(arr[i]);
}
int[] values = new int[k];
for (int i = 0; i < k; ++i) {
values[i] = queue.poll();
}
return values;
}
}
//leetcode submit region end(Prohibit modification and deletion)
测试用例
package leetcode.editor.cn;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
public class SolutionTest {
private Solution s;
@Before
public void setUp() throws Exception {
s = new Solution();
}
@Test
public void test1() {
int[] values = s.smallestK(new int[]{1, 3, 5, 7, 2, 4, 6, 8}, 4);
Arrays.sort(values);
Assert.assertTrue(values.length == 4);
int[] expected = new int[]{1, 2, 3, 4};
Assert.assertTrue(Arrays.equals(values, expected));
}
}