java - 我将如何删除最大元素并相应地移动值
问题描述
我有以下代码可以找到最大值并将值左移:
@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)]
解决方案
您的第二个循环必须以下列方式简化?您的 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];
}
推荐阅读
- html - 嵌套在有序列表中的无序列表
- java - 迭代可以是另一个对象的对象字段
- graphileon - 如何使我应用于节点的样式显示给访问 Graphileon 中相同数据存储的其他用户?
- python - 枢轴熊猫数据框具有多索引列
- menu - Shopify 汉堡菜单按钮在移动设备上不起作用(首次亮相主题)
- python - python中的内部类不影响程序正常运行
- c# - 来自数据库的实体框架 6 模型 - 禁用自动关联创建
- magento2 - magento 2.3.5p1 所有可配置产品显示缺货
- php - 多选项 echo php & mysql
- javascript - 渲染 rest api 响应(javascript 作为文本)