Prompt
You’re given an array of integers and an integer. Write a function that moves all instances of that integer in the array to the end of the array and returns the array.
The function should perform this in place (i.e., it should mutate the input array) and doesn’t need to maintain the order of the other integers.
Sample Input
array = [2, 1, 2, 2, 2, 3, 4, 2]
toMove = 2
Sample Output
[1, 3, 4, 2, 2, 2, 2, 2]
Solution
import java.util.*;
class Program {
public static List<Integer> moveElementToEnd(List<Integer> array, int toMove) {
// Write your code here.
int left = 0;
int right = array.size() - 1;
while (left < right) {
while (left < right && array.get(right) == toMove) {//B
right --;
}
if (array.get(left) == toMove) {
swap(left, right ,array);
}
left++;//C
}
return array;
}
public static void swap (int i, int j, List<Integer> array) {
int temp = array.get(i);//A
array.set(i,array.get(j));
array.set(j, temp);
}
}
# A
- 去了解array常用的内置函数
# B
还是见得少,做题的时候要画图,多画几步
# C
这种要注意,写对位置(每次看到爆栈 就很慌