首页 > 解决方案 > 我将如何删除最大元素并相应地移动值

问题描述

我有以下代码可以找到最大值并将值左移:

@Override
public void remove() throws QueueUnderflowException {
    int max = 0;
    int index = 0;
    if (isEmpty()) {
        throw new QueueUnderflowException();
    } else {
        for (int i = 0; i < tailIndex + 1; i++) {
            int current = ((PriorityItem<T>) storage[i]).getPriority();
            if (current > max) {
                max = current;
                index = i;
            }
        }

        for (int i = 0; i < tailIndex + 1; i++) {
            int current = ((PriorityItem<T>) storage[i]).getPriority();

            if (current >= max) {

                storage[i] = storage[i + 1];

            }
        }
        tailIndex = tailIndex - 1;
    }
}

但是,元素仅移动一次,因为我的 if 语句在值为最大值期间执行此操作,我将如何在不重复的情况下移动剩余的值。

这是输入:

[(y, 1), (o, 8), (u, 7), (o, 0)]

所需的输出:

(y, 1), (u, 7), (o, 0)]

当前输出:

[(y, 1), (u, 7), (u, 7)]

标签: javaarraysfor-looppriority-queue

解决方案


您的第二个循环必须以下列方式简化?您的 if 检查在第二个循环中不正确,您应该检查是否应该转移,不再检查优先级值,而仅检查索引

for (int i = 0; i < tailIndex + 1; i++) {
    if (i >= index) {
        storage[i] = storage[i + 1];
    }
}

或者更简单

for (int i = index; i < tailIndex + 1; i++) {
    storage[i] = storage[i + 1];
}

推荐阅读