猿问

为什么我的 Arraylist 一直在打印 [3,2]?

我正在尝试从整数数组中删除值的每个实例,并返回新整数数组的长度。输入为 [3,2,2,3],val 为 3。输出应为 [ 2,2],长度为 2。我不断得到 [3,2],但我正在通过数组删除 val。


    class Solution {

        public int removeElement(int[] nums, int val) {


            ArrayList<Integer> list = new ArrayList<Integer>(); 


            for(int i = 0; i < nums.length; i++) {

            list.add(nums[i]);

            }


            if(list.isEmpty()) {

            return 0;

            }


            for(int i = 0; i < list.size(); i++) {

                if(list.get(i) == val) {

                list.remove(i);

                }

            }

            return list.size();

        }

   }


胡子哥哥
浏览 120回答 3
3回答

江户川乱折腾

当您删除前 3 个时,您将拥有 i=0,接下来数组列表将调整大小,因此当您删除时,您需要执行 i - -。class Solution {&nbsp; &nbsp; &nbsp; &nbsp; public int removeElement(int[] nums, int val) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ArrayList<Integer> list = new ArrayList<Integer>();&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(int i = 0; i < nums.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; list.add(nums[i]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(list.isEmpty()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(int i = 0; i < list.size(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(list.get(i) == val) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; list.remove(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i--;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return list.size();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}

ABOUTYOU

您根本不需要调用 remove(像您一样删除时,没关系,但是例如,如果您在 foreach 循环中执行此操作,它会在 . 上崩溃ConcurrentModificationException。相反,您可以确定是否将 item 添加到结果中列出或不在第一个for循环内(我认为这更安全):ArrayList<Integer> list = new ArrayList<Integer>();&nbsp;for(int i = 0; i < nums.length; i++) {&nbsp; &nbsp; if (nums[i] != val) {&nbsp; &nbsp; &nbsp; &nbsp; list.add(nums[i]);&nbsp; &nbsp; }}return list.size();(我知道这不能直接回答你的问题)

三国纷争

您没有显示任何打印代码,但我假设您nums根据此方法返回的数字进行打印。这意味着您永远不会nums以任何方式进行更改,只需从那里打印前 n 个数字。您需要返回修改后的数组,而不仅仅是长度。
随时随地看视频慕课网APP

相关分类

Java
我要回答