How to remove elements from arraylist in linear time

sossu :

Great suggestions but some of them were not allowed (as streams), was very restricted task. Leo's algorithm was the thing I was looking for.

I'm trying to compare a specific letter on arraylist elements and need to remove every bigger letter from the arraylist. This has to be done in linear time, so remove() is not an option. How do I do it?

int deleted = 0;
int n = 0;

while (n < A.size()) {
    if (A.get(n).compareTo(x) > 0) {
        //removing here
        removed = removed + 1;
    }
    n++;
}

return removed;

A is an arraylist with random alphabetical letters and x is also a random letter. I need to remove every element from A which is bigger than the given x letter. Remove() is not an option because I need to do this in linear time instead of n^2.

Leo Aso :

If you want to remove elements in linear time from the list itself rather than creating a new list, then you can do it like this.

int i = 0;
int j = 0;

while (j < A.size()) {
    if (A.get(j).compareTo(x) > 0) {
        j++;
    } else if (i < j) {
        A.set(i++, A.get(j++));
    } else {
        i++;
        j++;
    }
}
int oldSize = A.size();
int newSize = oldSize - j + i;
A.subList(newSize, oldSize).clear();

This basically runs once through the list, shifting down elements to overwrite the elements that need to be filtered out. Then the list is trimmed down to size in the last three lines.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=164901&siteId=1