这是我到目前为止所做的,它适用于一些测试用例。该方法适用于某些阵列,但不适用于其他阵列。我对这个问题在哪里感到迷茫。方法描述在上述评论方法中。
/**
* Return an array of all the elements of a that are greater than val.
* If a contains no elements greater than val, this method returns an
* array of zero length.
*
* @param a the array to be searched
* @param val the reference value
* @return the elements a[i] such that a[i] > val
*
*/
public static int[] greater(int[] a, int val) {
if (a == null || a.length == 0) {
throw new IllegalArgumentException();
}
int x = 0;
int[] copy = Arrays.copyOf(a, a.length);
Arrays.sort(copy);
int nearest = copy[0];
for (int i = 0; i < copy.length; i++) {
if (Math.abs(nearest - val) > Math.abs(copy[i] - val)) {
nearest = copy[i];
x = i;
}
}
if ((x + 1) >= copy.length) {
int[] badAnswer = new int[0];
return badAnswer;
}
else {
int[] answer = new int[(copy.length - 1) - x];
int index = 0;
while (index < answer.length) {
answer[index] = copy[x + (index + 1)];
index++;
}
return answer;
}
}
这适用于使用JUnit进行此测试:
int a[] = {17,14,3,10,5,1,25};
@Test public void greaterTest() {
int d[] = Selector.greater(a, 5);
int p[] = {10, 14, 17, 25};
Assert.assertArrayEquals(d, p);
}
但不是这个:
int z[] = {-5,-2,0,4,8,15,50};
@Test public void greaterTest2() {
int d[] = Selector.greater(z, -99);
int p[] = {-5,-2,0,4,8,15,50};
Assert.assertArrayEquals(d, p);
也不是为了重复小于val的整数:
int z[] = {0, 0, 0, 0, 0};
@Test public void greaterTest2() {
int d[] = Selector.greater(z, 51);
int p[] = {};
Assert.assertArrayEquals(d, p);
}
关于如何在我的方法中解决这些差距的任何想法?
答案 0 :(得分:1)
我会使用JDK,只需要两行:
public static int[] greater(int[] a, int val) {
Arrays.sort(a);
return Arrays.copyOfRange(a, Math.abs(Arrays.binarySearch(a, val) + 1), a.length;
}
我省略了参数检查等,以强调这种方法的优雅和简洁。
在ideone上查看live demo。
答案 1 :(得分:1)
我看到我不是第一个答案,但我的注释:
private static int[] greater(int[] array, int v) {
// create space for the potential values greater than 'v'
int[] potentials = new int[array.length];
// an 'insertion point' in to the potentials array.
int ip = 0;
for (int a : array) {
// for each value in the input array....
if (a > v) {
// if it is greater than 'v', add it to the potentials
// and increment the ip insertion point.
potentials[ip++] = a;
}
}
// return the valid values from the potentials
return Arrays.copyOf(potentials, ip);
}
答案 2 :(得分:0)
public static int[] greater(int[] a, int val)
{
int[] greater = new int[a.length];
int greaterNumber = 0;
for (int i = 0; i < greater.length; i++)
if (a[i] > val)
greater[greaterNumber++] = a[i];
return Arrays.copyOf(greater, greaterNumber);
}