需要返回 k 个元素 a[i] 使得 ABS(a[i] - val) 是 k 个最大的评估。我的代码仅适用于大于 val 的整数。如果整数小于 val,它将失败。我可以在不导入 java.util.Arrays 以外的任何内容的情况下执行此操作吗?任何帮助都感激不尽!
import java.util.Arrays;
public final class Selector {
private Selector() {
}
public static int[] farthestK(int[] a, int val, int k) {// This line should not change
int[] b = new int[a.length];
for (int i = 0; i < b.length; i++) {
b[i] = Math.abs(a[i] - val);
}
Arrays.sort(b);
int[] c = new int[k];
int w = 0;
for (int i = b.length-1; i > b.length-k-1; i--) {
c[w] = b[i] + val;
w++;
}
return c;
}
测试用例:
import org.junit.Assert;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class SelectorTest {
/** Fixture initialization (common initialization
* for all tests). **/
@Before public void setUp() {
}
@Test public void farthestKTest() {
int[] a = {-2, 4, -6, 7, 8, 13, 15};
int[] expected = {15, -6, 13, -2};
int[] actual = Selector.farthestK(a, 4, 4);
Assert.assertArrayEquals(expected, actual);
}
}
There was 1 failure:
1) farthestKTest(SelectorTest)
arrays first differed at element [1]; expected:<-6> but was:<13>
FAILURES!!!
Tests run: 1, Failures: 1