Time O(n), space O(1)
ArrayList removeNegative(ArrayList a) {
if (a == null)
return a;
int nextNegative = 0, nextNonNegative = 0;
while (nextNegative < a.size()) {
if (a.get(nextNegative) >= 0) {
nextNegative++;
continue;
}
nextNonNegative = Math.max(nextNonNegative, nextNegative + 1);
while (nextNonNegative < a.size() && a.get(nextNonNegative) < 0) {
nextNonNegative++;
}
if (nextNonNegative == a.size()) {
break;
} else {
int tmp = a.get(nextNegative);
a.set(nextNegative, a.get(nextNonNegative));
a.set(nextNonNegative, tmp);
nextNegative++;
nextNonNegative++;
}
}
if (nextNegative < a.size()) {
a.subList(nextNegative, a.size()).clear();
}
return a;
}