(Basically two passes - one to find the elements to move and a second to move each element once to its new position.) The Java 8 removeIf solution is slightly more complex but avoids creating a new List. Your suggestion demonstrates a straight-forward solution to the problem - just copy the data over to a new structure while figuring out the new position of the element. The basic item removal operation has to maintain the data structure invariants for each loop of our solution, which (as you point out) requires relocation of all elements of higher indices. The reason for this is that we have introduced an extra constraint to the original problem when deciding to use item removal operations. Thus, solving the general problem of removing n elements from an array by using the basic removal operation will always be O(n^2). Ignoring any language or implementation details and just considering the problem per se, it is easy to see that removal of elements in an array is O(n) (since it entails relocation of O(n) elements). I think that your comment beautifully illustrates the reason why the The Java 8 implementation is more efficient. Thus, none of the solutions are mine in any sense. I did not intend to convey that I have created any novel solution to the removal problem, on the contrary I meant to point out that the Java 8 remove operation is O(n).
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |