截止到目前我已经写了 500多道算法题,其中部分已经整理成了pdf文档,目前总共有1000多页(并且还会不断的增加),大家可以免费下载

LeetCode 26. 删除有序数组中的重复项_LeetCode
LeetCode 26. 删除有序数组中的重复项_leetcode_02

LeetCode 26. 删除有序数组中的重复项_LeetCode_03
​​​视频链接​

来看下代码

//双指针解决
public int removeDuplicates(int[] A) {
//边界条件判断
if (A == null || A.length == 0)
return 0;
int left = 0;
for (int right = 1; right < A.length; right++)
//如果左指针和右指针指向的值一样,说明有重复的,
//这个时候,左指针不动,右指针继续往右移。如果他俩
//指向的值不一样就把右指针指向的值往前挪
if (A[left] != A[right])
A[++left] = A[right];
return ++left;
}

或者还可以换一种解法,其实原理都是一样的。

public int removeDuplicates(int[] A) {
int count = 0;//重复的数字个数
for (int right = 1; right < A.length; right++) {
if (A[right] == A[right - 1]) {
//如果有重复的,count要加1
count++;
} else {
//如果没有重复,后面的就往前挪
A[right - count] = A[right];
}
}
//数组的长度减去重复的个数
return A.length - count;
}