题目:
给定一个排序过的数组,要求in place的移除重复元素,返回处理后的数组长度
思路:
前后指针,一遍遍历数组即可
要点:
1 双指针,一开始两个指针i,j都指向第一个元素,特别注意1,1,2 删除1的情况
2 明确i的作用是指向下一个要被替换的位置,j的作用是找到下一个valid的数,然后用j指向的数来替换i指向的数
package Level1;
import java.util.Arrays;
/**
* Remove Element
*
* Given an array and a value, remove all instances of that value in place and
* return the new length.
*
* The order of elements can be changed. It doesn't matter what you leave beyond
* the new length.
*/
// 这种题必须在纸上模拟一遍
public class S27 {
public static void main(String[] args) {
int[] A = {1,1,2,3};
int elem = 1;
System.out.println(removeElement(A, elem));
System.out.println(Arrays.toString(A));
}
// O(n)
public static int removeElement(int[] A, int elem) {
if(A.length == 0){
return 0;
}
if(A.length == 1){
if(A[0] == elem){
return 0;
}else{
return 1;
}
}
int i = 0; // i用来标示下一个要被替换的位置
int j = 0; // j用来找到下一个valid的数
// 双指针固定格式
while(i<A.length && j < A.length){
// j跳过invalid的数,直到找到valid的数
if(A[j] == elem){
j++;
}else{
A[i] = A[j]; // 替换invalid的数
i++; // 更新标示
j++;
}
}
return i;
}
}
public class Solution {
public int removeElement(int[] A, int elem) {
int len = A.length;
if(len == 0){
return 0;
}
if(len==1 && A[0]==elem){
return 0;
}
int p=0, q=0;
// 1 1 2
while(q != len){
if(A[q] == elem){
q++;
}else{
A[p] = A[q];
p++;
q++;
}
}
return p;
}
}