【发布时间】:2020-12-23 08:41:30
【问题描述】:
我有一个任务,创建一个获取字符串数组元素的方法,检查是否存在重复项,然后删除它(我尝试使用“null”),然后将所有其他元素移向索引值 [0] 以缩小差距。
现在看起来像这样:
public static boolean deleteTask() {
boolean removed = false;
for (int pos = 0; pos < todos.length; pos++) {
if (todos[pos].equals(titel)) {
todos[pos] = null;
removed = true;
if (removed){
//set pos+1 = pos to reduce each value -1.
//repeat process for each index [10]
}
}
}
return removed;
}
}
在图片中,我展示了我看到的结果。 例如。 pos.4 是重复的 - 然后它被设置为 null。现在必须将以下所有索引更改为 -1 以填补空白。 显然,索引然后设置回 456 而不是 567 这只是为了说明字符串的移动。
你能帮我在 [pos] null 之后向 -1 方向移动索引吗?
如果您可以帮助对 2 个以上的重复项做同样的事情,那就更好了。
【问题讨论】:
-
您知道被删除元素的位置,并且您知道基本的
for循环是什么。你也知道算法是如何的,你只是画了它。那么这里到底有什么不清楚的地方呢? -
[pos +1] = [pos]... 为什么 +1? -
在 [pos] 4/null 上,我想从右边/下一个索引(或当前位置 +1 [pos+1] )中取出字符串,即图片中的 5 和将其拉回左侧当前索引位置 [pos]/4 。然后对 5.6.7 等执行相同操作,直到 todos.length-1