给你一个数组array和一个值(target),需要原地移除所有数值等于target的元素,并返回移除后数组的新长度
相关题目:
26.删除排序数组中的重复项、(已做)
283.移动零、(已做)
844比较含退格的字符串、(已做)
977.有序数组的平方(已做)
public class LC27_remove_element {
public static void main(String[] args) {
int[] array = {5, 9, 5, 36, 84, 96, 125, 456, 535};
System.out.println(remove_element(array,5));
System.out.println(remove_element_doblePointer(array,5));
}
private static int remove_element(int[] array, int target) {
int count = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
count += 1;
for (int j = i+1; j < array.length; j++) {
array[j-1] = array[j];
}
i--;
}
}
return array.length-count;
}
private static int remove_element_doblePointer(int[] array, int target) {
//慢指针slowIndex
int slowIndex = 0;
for (int fastIndex = 0; fastIndex < array.length; fastIndex++) {
if (array[fastIndex] != target) {
array[slowIndex++] = array[fastIndex];
}
}
return slowIndex;
}
}



