我有一个ArrayList
integers
,我想要删除所有前导零,代码似乎没问题,但是你得到了不寻常的输出。
输入:
0 0 0 1 9 9
输出:
0 1 9 9
预期输出:
1 9 9
public class Solution {
public ArrayList<Integer> plusOne(ArrayList<Integer> a) {
int flag=0;
//System.out.println(a.size()+" "+a.get(2));
for(int i=0;i<a.size();i++)
{
if(flag==0)
{
//System.out.println("val of i="+i+" "+a.get(i));
if(a.get(i)==0){
a.remove(i);
//System.out.println(flag);
}
else
{
//System.out.println("flag="+flag+" i="+i+" value"+a.get(i));
flag=1;
//System.out.println("flag="+flag+" i="+i+" value"+a.get(i));
}
}
if(flag==1)
break;
}
System.out.println();
return a;
}
}
答案 0 :(得分:5)
您可以通过搜索第一个非零值删除前导零,然后清除前面的子列表:
Iterator<Integer> it = list.iterator();
int i = 0;
while (it.hasNext() && it.next() == 0) {
++i;
}
list.sublist(0, i).clear();
像这样删除列表块比一次删除一个元素更有效。例如如果你一次删除一个,ArrayList
将每次将所有尾部元素移动一个位置,因此删除将为O(n ^ 2)。
答案 1 :(得分:3)
问题是i
正在递增而a.size()
正在缩小。当i==0
删除元素0
以便所有值向下移1时,接下来删除元素1,但元素0也为0,所以你跳过这个。即你只删除了一半的前导零。
BTW您应该可以通过在调试器中单步执行代码来确认这一点。帮助您理解您的代码并找到错误就是它的用途。
最简单的改变是
for (int i = 0, max = a.size(); i < max; i++)
和
// you only want to check the first element.
if (a.get(0) == 0)
a.remove(0);
更有效的方法是找到第一个不为0的元素并返回一个子列表
public static List<Integer> trimLeadingZeros(List<Integer> list) {
for (int i = 0; i < list.size(); i++)
if (list.get(i) != 0)
return list.subList(i, list.size());
return Collections.emptyList();
}
答案 2 :(得分:3)
问题在于,当您迭代它时,您正在从列表中删除元素。当i = 0
:
a.remove(i);
删除列表的第一个元素并移动所有元素:第二个变为第一个,然后等。然后在for
循环中,i
之后设置为1。因此,第二个元素被忽略:它成为删除操作后的第一个元素,i
跳过它,因为它已经递增。
丑陋的解决方案是在i--;
之后立即a.remove(i);
来解释这一转变。
但是,更好的解决方案是使用ListIterator
:
public ArrayList<Integer> plusOne(ArrayList<Integer> a) {
ListIterator<Integer> it = a.listIterator();
while (it.hasNext() && it.next() == 0) {
it.remove();
}
return a;
}
此代码使用listIterator()
检索它。虽然仍有元素且下一个元素为0,但我们会使用remove()
将其删除。
答案 3 :(得分:0)
逻辑:任何时候你看到0,从那一点循环到结束,如果在那个循环中你看到除0以外的任何东西,那么就从那个循环中突破。
代码:
//a is arrayList;
int count = 0;
for(int c = b; c < size; c++){
if(a.get(c) == 0 )
{
count++;
}
}
//size = 10,saw zero at 6th position that means leading zeros has to be 4,
// b is when I first saw 0
if(count == (size -b)) {}
else {
//else we just copy
ret.add(b, a.get(b));
}
答案 4 :(得分:0)
循环遍历ArrayList,如果遇到0,只需删除它。
while (i < a.size() - 1 && a.get(i) == 0) {
a.remove(i);
}