Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
What if duplicates are allowed at most twice?
For example,
Given sorted array A =
Given sorted array A =
[1,1,1,2,2,3],
Your function should return length =
5, and A is now [1,1,2,2,3].
依旧是两个指针,并且用一个count来记录重复次数。 遍历一次 时间O(n)空间 O(1)
public class Solution {
public int removeDuplicates(int[] nums) {
int index = 1;
int count = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i - 1]) {
count++;
if (count >= 3) {
continue;
}
} else{
count = 1;
}
nums[index++] = nums[i];
}
return index;
}
}
没有评论:
发表评论