思路:
利用双指针,一个fast指针,一个slow指针。比较 fast 和 slow位置的元素是否相等。 如果相等,slow 后移 1 位 如果不相等,将 fast位置的元素复制到 slow+1 位置上,slow 后移一位,fast 后移 1 位 重复上述过程,直到 fast 等于数组长度。 返回 slow + 1,即为新数组长度。
题解:
class Solution {
public int removeDuplicates(int[] nums) {
if (nums.length < 2){
return nums.length;
}
int slow = 1;//建立两个指针
int fast = 1;
while (fast < nums.length){//遍历
if (nums[fast] != nums[fast-1]){
nums[slow] = nums[fast];
slow++;
fast++;
}else {
fast++;
}
}
return slow;
}
}