题目:
给定一个排序过的数组,要求in place的移除重复元素,返回处理后的数组长度
思路:
前后指针,一遍遍历数组即可
变型题是:移除元素后,使得重复出现的元素最多出现2次
http://blog.youkuaiyun.com/fightforyourdream/article/details/12883543
/**
*
* Remove Duplicates from Sorted Array
*
* Given a sorted array, remove the duplicates in place such that each element appear
* only once and return the new length.
*
* Do not allocate extra space for another array, you must do this in place with
* constant memory.
*
* For example, Given input array A = [1,1,2],
*
* Your function should return length = 2, and A is now [1,2].
*
*/
public class S26 {
public static void main(String[] args) {
int[] A = {1, 1, 2};
System.out.println(removeDuplicates(A));
}
public static int removeDuplicates(int[] A) {
int len = A.length;
if(len < 2){
return len;
}
// i遍历数组,j指向待检验是否与i相同的下一个数
int i = 0, j = 1;
while(i<len && j<len){
if(A[i] == A[j]){ // 如果出现相同
j++; // 则j继续往前找,直到找到不同于A[i]数
}else{
i++; // i跳动要被覆盖的重复那个数
A[i] = A[j]; // 用非重复的j覆盖重复的i
j++; // 更新待检验的j
}
}
// 返回长度是下标加1
return i+1;
}
}
public class Solution {
public int removeDuplicates(int[] A) {
int len = A.length;
if(len <= 1){
return len;
}
int p = 0, q = 0;
while(q < len){
if(A[p] == A[q]){
q++;
}else{
p++;
A[p] = A[q];
q++;
}
}
return p+1;
}
}