【问题标题】:using Binary search with a comparator to find first occurance使用带有比较器的二进制搜索来查找第一次出现
【发布时间】:2015-05-17 10:09:07
【问题描述】:

我试图为算法和数据结构类进行自动完成分配,在分配中它要求您创建一个类来查找键的第一次出现和键的最后一次出现。

我遇到的问题是我不明白如何在这个问题中实现比较器,我在设置二进制搜索时遇到问题,因为当我尝试比较键

// 返回 a[] 中与搜索键相等的第一个键的索引,如果没有这样的键,则返回 -1。使用二分查找

    public static <Key>int firstIndexOf(Key[] a, Key key, Comparator<Key> comparator) {

        int low = 0;
        int high = a.length - 1;
        int result = -1;

        while (low <= high) {
            int mid = (low + high) / 2;
            if (key == a[mid]) {
                result = mid;
                high = mid - 1;
            }else if (key < a[mid]) { //**<--- throws bad operand type for binary operator**         
            high = mid - 1;   // key is probable to lie before mid element
            }else {
           low = mid +1;  // key is probable to lie after mid 
           }
        }
            return result;
}

我应该传递的有问题的比较器就像这样,它使用字符串中的子字符串方法查找 rValue,以查看两个对象之间的前缀顺序是否匹配。再说一次,我不知道我是否一开始就这样做了,但这不是问题,问题是我将如何在其他类中实现这一点

// 按字典顺序比较术语,但只使用每个查询的前 r 个字符。

 public static class prefixOrder implements Comparator<Term> 
    { public prefixOrder(int r){
      rValue = r;
    }

    @Override
    public int compare(Term v, Term w){
    return  v.queryItem.substring(rValue).compareTo(w.queryItem.substring(rValue));
    }

    }

作业链接 https://www.cs.princeton.edu/courses/archive/fall14/cos226/assignments/autocomplete.html

【问题讨论】:

标签: java comparator binary-search


【解决方案1】:

你不能像在 Java 中那样写 key &lt; a[mid],而是调用比较器的 compare 方法:

if (comparator.compare(key, a[mid]) < 0) ...

它的工作原理是这样的:比较方法根据比较结束的方式返回正/零/负值。我记得是这样的:

a OP b --> comparator.compare(a, b) OP 0

其中 OP 是 >、>=、 中的任何一个

此外,您可能希望将方法声明更改为:

public static <Key>int firstIndexOf(Key[] a, Key key, Comparator<? super Key> comparator)

例如,您可以使用 Animal 比较器从 Dogs 数组中选择最小值,其中 Dog extends Animal。 (阅读更多关于wildcards的信息。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    • 2020-10-25
    • 2014-06-21
    • 2022-11-25
    • 1970-01-01
    • 2019-04-13
    相关资源
    最近更新 更多