In Java, we have an array int[] a = new int[10000000]; fully filled in with arbitrary numbers. Quite often in code we need to remove an arbitrary subsequence: that is a set of elements that may be non-contiguous.
The reason to use int[] over LinkedList is a speed gain while passing through elements. Currently there is no removal of elements, so lots of rubbish is stored for the time of running application. Removing elements may give a speed-up, so quite an interesting question.
How to remove a subseqence from an array in a fastest possible way?
It depends on whether you want to shorten the array or if you can allow unused elements at the end of the array. The tool for this is
System.arraycopy. To shorten the array, you will need to allocate a new one:To just compact an array:
You don’t have to worry about overlapping ranges;
arraycopycorrectly deals with those.If you have a discontinuous range of elements to remove, you can either generalize one of these solutions (less moving things around, but more complex code) or you can remove each continuous block separately (easier to program but you will be moving around data that you will be discarding).
If you have scattered indices to remove, I would do it by hand. The design depends on whether it is scattered individual indices or whether it is a collection of ranges. With the latter (this is untested, but it should give you the idea):