0

这种方法由于限制不能使用ArrayLists。该方法接受一个数组,要查找的所需值,然后是一定数量的邻近值。它仅使用整数和整数数组。这是我到目前为止所拥有的

/**
    * Return the k elements of a nearest to val.
    * The array a is not changed as a result of calling this method.
    * This method throws an IllegalArgumentException if k is negative.
    * This method returns an array of zero length if k == 0 or if
    * k > a.length.
    *
    * @param a the array to be searched
    * @param val the reference value
    * @param k the number of near elements to identify
    * @return the k elements a[i] such that ABS(a[i] - val)
    * are the k smallest evaluations
    *
    */
   public static int[] nearestK(int[] a, int val, int k) {

      int x = 0;
      int[] answer = new int[k];

      if (k < x || a.length == 0 || a == null)
      {
         throw new IllegalArgumentException();
      }

      if (k == 0 || k > a.length) 
      {
         int[] badAnswer = new int[0];
         return badAnswer;
      }

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

      }

      int index = 0;
      while (index < answer.length) {

         answer[index] = nearest;
         nearest = copy[x + (index + 1)];
         index++; 

      }
      return answer;




 }

这种方法有时有效,但我开始意识到它只在所需元素之后使用值。

即 int[1,3,5,7,10,11,12} 这种方法,如果搜索 6,具有 3 个最接近的值,只会返回 7,10,11 作为数组。这显然是不正确的。我对java很陌生,所以在这一点上,我想知道有什么替代方法或纠正这种方法的方法。

4

1 回答 1

1

这是一个聪明的答案:不是按自然顺序对数组进行排序,而是根据到val. 然后,您需要做的就是选择第一个k元素:

public static int[] nearestK(int[] a, int val, int k) {
    // omitted your checks for brevity
    final int value = val; // needs to be final for the comparator, you can also make the parameter final and skip this line
    Integer[] copy = new Integer[a.length]; // copy the array using autoboxing
    for (int i = 0; i < a.length; i++) {
        copy[i] = a[i];
    }
    Arrays.sort(copy, new Comparator<Integer>() { // sort it with a custom comparator
        @Override
        public int compare(Integer o1, Integer o2) {
            int distance1 = Math.abs(value - o1); 
            int distance2 = Math.abs(value - o2); 
            return Integer.compare(distance1, distance2);
        }
    });
    int[] answer = new int[k]; // pick the first k elements
    for (int i = 0; i < answer.length; i++) {
        answer[i] = copy[i];
    }
    return answer;
}
于 2013-09-02T23:51:08.777 回答