user6038386 user6038386 - 4 months ago 9
Java Question

Remove Leading zeroes from an ArrayList of integers

I have an

ArrayList
of
integers
, I want to remove all the leading zeroes, code seems all right but U am getting unusual output.

Input:


0 0 0 1 9 9


Output:


0 1 9 9


Expected output:


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;
}
}

Answer

You can remove the leading zeros by just searching for the first non-zero value, and then clearing the preceding sublist:

Iterator<Integer> it = list.iterator();
int i = 0;
while (it.hasNext() && it.next() == 0) {
  ++i;
}
list.sublist(0, i).clear();

Removing a block of the list like this can be more efficient than removing the elements one at a time. e.g. if you removed them one at a time, ArrayList would shift all of the tail elements one position along each time, so the removal would be O(n^2).