【问题标题】:Understanding this remove method solution with arrayList [duplicate]使用 arrayList 了解此删除方法解决方案 [重复]
【发布时间】:2017-01-30 22:58:43
【问题描述】:

此方法的职责是从 arrayList 中删除所有出现的值 toRemove。剩余的元素应该只是移向列表的开头。 (大小不会改变。)末尾的所有“额外”元素(无论列表中出现了多少次 toRemove)都应该用 0 填充。该方法没有返回值,如果列表没有元素,它应该没有效果。 不能使用 ArrayList 类中的 remove() 和 removeAll()。

方法签名是:

public static void removeAll(ArrayList<Integer> list, int toRemove);

解决办法:

public static void removeAll(ArrayList<Integer> list, int toRemove) {
    for (int i = 0; i < list.size(); i++) {
        if (list.get(i) = toRemove) {
            for (int j = i + 1; j < list.size(); j++) {
                list.set(j - 1, list.get(j));
            }
            list.set(list.size() - 1, 0);
            i--;
        }
    }

我理解第一个 for 循环和 if 语句。因为人们想逐一遍历整个arrayList,并且对于arrayList中存在数字的每个索引,检查它是否是,实际上是toRemovee整数。在这一点之后,我迷路了。

为什么还有一个 for 循环? 为什么我们要取前面的循环变量并给它加 1? 为什么在第二个循环中我们使用参数“list”并使用 set 方法? 为什么 j - 1? 为什么 list.get(j)? 为什么在第二个循环结束后有这条线: list.set(list.sise () - 1, 0) ? 为什么我--?

有很多活动部件,我想了解其中的逻辑。

谢谢

【问题讨论】:

  • 这不会编译。
  • “为什么要另一个 for 循环?” 满足 “剩余元素应该只是移向列表开头”的要求。也许你应该附加一个断点并遍历代码,看看它是如何变化的
  • @MadProgrammer 谢谢。我不明白它是如何转移到列表开头的。
  • @Jun 那你需要看看ArrayList#set 的JavaDocs 看看它做了什么

标签: java arraylist


【解决方案1】:

首先 if 语句是不正确的赋值操作。您需要将 = 更改为 ==。我已经解释了代码中的每个步骤-

public static void removeAll(ArrayList<Integer> list, int toRemove) {
    //start with the first number in the list until the end searching for toRemove's
    for (int i = 0; i < list.size(); i++) {
        //if the value at i is the one we want to remove then we want to shift
        if (list.get(i) == toRemove) {
            //start at the index to the right until the end
            //for every element we want to shift it the element to its left (i == j - 1)
            for (int j = i + 1; j < list.size(); j++) {
                //change every value to whatever was to the right of it
                //this will overwrite all values starting at the index where we found toRemove
                list.set(j - 1, list.get(j));
            }

            //now that everything is shifted to the left, set the last element to a 0
            list.set(list.size() - 1, 0);
            //decrement to adjust for the newly shifted elements
            // this accounts for the case where we have two toRemoves in a row
            i--;
        }
    }
}

在这个函数的末尾,任何匹配 toRemove 的值都会被“移除”,方法是每次找到值时将 arraylist 向左移动,最后一个元素将被设置为 0。

例子

removeAll([1,2,3,4,5,5,6,7,8,5,9,5], 5)

输出

[1,2,3,4,6,7,8,5,9,0,0,0] 

【讨论】:

  • 非常感谢!我对 j - 1 的作用和 size() - 1 有点困惑。这两部分让我最困惑。
【解决方案2】:

请参阅以下内容以了解详细信息(从 5:50 或 5:57 开始)

https://www.youtube.com/watch?v=qTdRJLmnhQM

您需要第二个 for 循环,以获取删除元素之后的所有元素并将其向左移动一个,因此基本上它会填充删除它留下的空白空间,所以这就是做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 2017-09-13
    • 2013-08-31
    • 2013-04-06
    • 1970-01-01
    • 2022-10-31
    • 1970-01-01
    相关资源
    最近更新 更多