在数组中搜索一定数量的大于一个整数的整数 [英] Searching an array for certain number of integers greater than one integer

查看:60
本文介绍了在数组中搜索一定数量的大于一个整数的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了此方法来查找大于数组中特定值的值的数量,并且该方法适用于具有正整数的错误,但是当我尝试此测试用例时,它失败了.

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

这是我与JUnit一起运行的测试用例.

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?

推荐答案

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

这篇关于在数组中搜索一定数量的大于一个整数的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆