Searching an array for certain number of integers greater than one integer

冷暖自知 提交于 2019-12-12 02:39:47

问题


I have written this method to find the number of values that are greater than a specific value in an array and it works with arrrays that have positive integers but when I tried this test case it failed.

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;
   }

Here is the test case I ran with JUnit.

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


@Test public void numGreaterTest1() {

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

}

Any ideas on where I went wrong?


回答1:


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;
   }


来源:https://stackoverflow.com/questions/18580623/searching-an-array-for-certain-number-of-integers-greater-than-one-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!