class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length <= 2){
return nums.length;
}
int cnt = 1, end = 1;
for(int i = 1; i < nums.length; i++){
if(nums[i] == nums[i - 1]){
cnt++;
if(cnt <= 2){
nums[end++] = nums[i];
}
}else{
cnt = 1;
nums[end++] = nums[i];
}
}
return end;
}
}
改成模板:
class Solution {
public int removeDuplicates(int[] nums, int k) {
if(nums.length <= k){
return nums.length;
}
int cnt = 1, end = 1;
for(int i = 1; i < nums.length; i++){
if(nums[i] == nums[i - 1]){
cnt++;
if(cnt <= k){
nums[end++] = nums[i];
}
}else{
cnt = 1;
nums[end++] = nums[i];
}
}
return end;
}
}