题目传送地址:https://leetcode.cn/problems/remove-duplicates-from-sorted-array-ii/
运行效率
代码如下:
class Solution {
public static int removeDuplicates(int[] nums) {
int left = 0;
int right = 1;
int count=0;
//注意:nums的长度是动态变化的,所以下面的while条件里要写成小于 nums.length-count
while (right < nums.length-count && left < nums.length-count) {
if (nums[left] == nums[right]) {
if (right - left == 2) {
moveForward(nums, right);
count++;
} else {
right++;
}
continue;
}
if (nums[left] != nums[right]) {
left = right;
right++;
}
}
return nums.length-count;
}
public static void moveForward(int[] nums, int index) {
for (int i = index; i < nums.length; i++) {
nums[i - 1] = nums[i];
}
}
}