首页 > 解决方案 > 所以我对以下方法有疑问,不知道为什么它不适用于 9 个案例中的 3 个?

问题描述

编写一个名为 isConsecutive 的方法,该方法接受整数的 PriorityQueue 作为参数,如果队列包含从队列前面开始的连续整数序列,则返回 true。连续整数是一个接一个的整数,如 5、6、7、8、9 等,因此如果队列存储 [7、8、9、10、11],您的方法应该返回 true。(如果传递了一个空队列,也返回 true。)如果您的方法在计算过程中修改了队列的状态,它应该在返回之前恢复队列。您可以使用一个堆栈或队列作为辅助存储。

public boolean isConsecutive(PriorityQueue<Integer> q){

    if(q.isEmpty()){return true;}
    boolean checker = true;
    Object[] other = q.toArray();
    for(int i = 0; i < other.length-1; i++){
        if (checker == false) return checker;
        checker = (int) other[i] < (int) other[i+1];
    }
    return checker;
}

标签: javastackqueuepriority-queue

解决方案


推荐阅读