在 Java 中查找带比较器的最大数组元素

Find largest array element with a Comparator in Java

所以我星期二要考试算法和数据,但我不能从过去的论文中解决这个问题。

Write a Java static method called greatest which takes an array of objects and a Comparator object which can order objects of the array’s element type, and returns whichever element from that array is greatest according to the order given by the Comparator object. You may assume the array is of length at least 1. Your code must use no method from Java’s API except the method compare from type Comparator.Your method must be generic, so the array could have any non-primitive element type.

我的尝试:

public static void greatest(Object[] a, Comparator<Object> x) {
        for (int i = 0; i < a.length; i++) {
            x.compare(a[i], a[i+1]));
        }
    }

但正如您可能看到的那样,我很无能,而且我确定我的尝试是错误的!任何帮助都会很棒。我在网上查看了比较器,但它们似乎只针对特定数据类型,而这是针对任何非原始元素类型的。

您的方法应该是通用的,并且 return 是一个结果。 这是解决方案的一部分,您只需添加一些内容即可完成。

public static <T> T greatest(T[] a, Comparator<? super T> comp) {
    T greatest = a[0];
    for(int i = 1; i < a.length; i++) {
    }
    return greatest;
}

Compare<T>是一个通用接口,正如参数<T>所见。 T 可以是任何 class。因为下面的方法接受类型为 Comparator<T> 的参数,所以它可以接受任何实现此接口的比较器。

请注意,该数组包含 T 类型的对象。这是必要的,因为 Comparator 只知道如何比较这种类型的对象。

public static <T> T greatest(T[] a, Comparator<? super T> x) {
    T greatest = a[0];
    for (int i = 1; i < a.length; i++) {
        if (x.compare(a[i], greatest) > 0) {
            greatest = a[i];
        }
    }
    return greatest;
}
  1. 用第一个元素a[0]初始化当前最大值
  2. 遍历数组并将当前元素与最大值进行比较
  3. 如果当前元素大于最大值,则为新的最大值
  4. return最大值

该方法必须是通用的(在文本中 "object" 被误导)。它还需要 return 结果(在本例中是输入类型的对象,但某些解决方案可能 return 对象的索引)。

因此函数声明将如下所示:

public static <T> T greatest(T[] objects, Comparator<T> comparator)

然后你需要找到最大的那个。这只需记住您迄今为止见过的最大的一个即可。一旦一个元素变大,记住新的:

{
    assert objects.length >= 1;
    T pivot = objects[0]; // assume the first is biggest
    for(T o : objects) // no good way to start with second
    {
        if (comp.compare(o, pivot) > 0) // if o is bigger
            pivot = o;
    }
    return pivot;
}

代码未经编译和测试。

试试这个:

public static T greatest(T[] a, Comparator<T> x) {
    T temp = a[0];
    for (int i = 0; i < a.length;i++) {
        if (x.compare(temp,a[i]) <= 0) {
            temp = a[i];
        }
    }
    return temp;
}