|
| 1 | +/* |
| 2 | + Move Element to end |
| 3 | + Sample Input : [1, 0, 3, 0, 0, 5] To move: 0 |
| 4 | + Output : [1, 3, 5, 0, 0, 0] |
| 5 | +
|
| 6 | + This is a function called MoveElementToEnd that takes an array of integers array and an integer toMove as input, |
| 7 | + and returns a modified array with all instances of toMove moved to the end of the array. |
| 8 | +
|
| 9 | + The function first initializes an integer variable index to 0, which will keep track of the index of the first |
| 10 | + element in the array that is not equal to toMove. Then, it loops through the array using a for loop, and if the |
| 11 | + current element is not equal to toMove, it replaces the element at the index position with the current element |
| 12 | + and increments the index variable by 1. This effectively shifts all elements that are not equal to toMove to the |
| 13 | + beginning of the array. |
| 14 | +
|
| 15 | + Next, the function loops through the remaining elements of the array (i.e., those that were not overwritten in |
| 16 | + the previous loop), and sets their value to toMove. This effectively moves all instances of toMove to the |
| 17 | + end of the array. |
| 18 | +
|
| 19 | + Finally, the modified array is returned. |
| 20 | +
|
| 21 | + O(n) time | O(1) space - where n is the length of the array |
| 22 | +*/ |
| 23 | + |
| 24 | +import java.util.List; |
| 25 | + |
| 26 | +public class MoveElementToEnd { |
| 27 | + public static List<Integer> moveElementToEnd(List<Integer> array, int toMove) { |
| 28 | + int index = 0; // initialize a variable to keep track of the index where elements should be moved to |
| 29 | + for (int i = 0; i < array.size(); i++) { // loop through the entire array |
| 30 | + if (array.get(i) != toMove) { // check if the current element is not equal to the element to be moved |
| 31 | + array.set(index, array.get(i)); // move the current element to the left side of the array by replacing the element at the current index (index) with the current element (array.get(i)) |
| 32 | + index++; // increment the index variable by 1 to keep track of the index where the next non-target element should be moved |
| 33 | + } |
| 34 | + } |
| 35 | + for (int i = index; i < array.size(); i++) { // loop through the remaining elements in the array from index to the end |
| 36 | + array.set(i, toMove); // set each element to be the target element |
| 37 | + } |
| 38 | + return array; // return the modified array |
| 39 | + } |
| 40 | +} |
0 commit comments