0

我编写了这个方法来查找大于数组中特定值的值的数量,它适用于具有正整数的数组,但是当我尝试这个测试用例时它失败了。

public static int numGreater(int[] a, int val) {
      if (a == null || a.length == 0) {

         throw new IllegalArgumentException();         
      }



      int[] copy = Arrays.copyOf(a, a.length);
      Arrays.sort(copy);

      int answer = 0;

      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]; 
            answer = (copy.length - 1) - i;
         }       
      }         


      return answer;
   }

这是我用 JUnit 运行的测试用例。

int z[] = {-5,-2,0,4,8,15,50};


@Test public void numGreaterTest1() {

      Assert.assertEquals(7, Selector.numGreater(z, -99));

}

关于我哪里出错的任何想法?

4

1 回答 1

0
public static int numGreater(int[] a, int val) {
      if (a == null || a.length == 0) {
         throw new IllegalArgumentException();         
      }

      int answer = 0;

      for (int i = 0; i < a.length; i++) {
         if (a[i]>val) {
            answer++;
         }       
      }         


      return answer;
   }
于 2013-09-02T20:59:27.597 回答