繁体   English   中英

ArrayList删除第一个元素

[英]ArrayList Removing first element

这是给定的问题:给定一个非负数表示为数字数组,

将数字加1(增加数字所代表的数字)。

存储数字使得最高有效数字位于列表的开头。

例:

如果向量有[1,2,3]

返回的向量应为[1,2,4]

因为123 + 1 = 124。

这是我的代码:

 public class Solution {
    public ArrayList<Integer> plusOne(ArrayList<Integer> A) {       
        int carry = 1;
        int length = A.size();
        ArrayList result = new ArrayList();

        for( int i = length - 1; i >=0; i-- ){
            int val = A.get(i) + carry;
            result.add(0,val % 10);
            carry = val / 10;
        }

        if (carry == 1){
            result.add(0,1);
        }

        for (int j = 0; j < result.size(); j++){
            if(result.get(j).equals(0))
                result.remove(j);
            else
                break;
       }

        return result;

    }
  }

但是,在测试用例中:A:[0,6,0,6,4,8,8,1]

它说我的函数返回

6 6 4 8 8 2

而正确的答案是

6 0 6 4 8 8 2

我不知道我的代码有什么问题。

谢谢!

if(result.get(j).equals(0))
    result.remove(j);
else
    break;

如果每个其他索引包含0,这将失败。这是发生的事情:

0 6 0 6 4 8 8 2
^ (j = 0)

0将被删除, j增加1。

6 0 6 4 8 8 2
  ^ (j = 1)

然后删除此0,跳过数组中的前6个。 要解决此问题,请将代码段更改为:

if(result.get(j).equals(0))
    result.remove(j--);
else
    break;

这可以补偿何时删除索引,以便j在任何删除的0之后不会立即跳过该数字。

查看循环和arraylist中的类似问题, 并删除指定索引处的元素

更简单的做法

while (!result.isEmpty() && result.get(0).equals(0)) {
  result.remove(0);
}

这将继续删除最左边的0,直到没有最多的零被删除。

你的最后一个for循环是从结果ArrayList<Integer>删除0 删除该循环后,您将获得完美的输出

public static ArrayList<Integer> plusOne(ArrayList<Integer> A) {       
    int carry = 1;
    int length = A.size();
    ArrayList result = new ArrayList();

    for (int i = length - 1; i >= 0; i--) {
        int val = A.get(i) + carry; //2 8
        result.add(0, val % 10);    // 2 8
        carry = val / 10;  
    }

    if (carry == 1) {
        result.add(0, 1);
    }

//  for (int j = 0; j < result.size(); j++) {
//      if (result.get(j).equals(0))
//          result.remove(j);
//      else
//          break;
//  }

    for (boolean isZero = true; isZero; ) {
        isZero = result.get(0).equals(0);

        if(isZero)
            result.remove(0);
    }

    return result;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM