80. Remove Duplicates from Sorted Array II
给定一个有序的数组nums,删除2次以上重复内容,使每个元素只出现1/2次并返回新的长度。
不要为其他数组分配额外空间,您必须通过在O(1)额外内存中就地修改输入数组来实现此目的。
Given nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
It doesn't matter what you leave beyond the returned length.
思路:数组有序,重复数组必定相邻!
加入一个判断是否两次的count,其它和27是一样的。
JAVA 2ms
class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length <= 2) return nums.length;
int limit = 1;
int count = 0;
for(int i = 1; i<nums.length; i++){
if(nums[i] == nums[count]){
if(limit < 2){ // duplicated, but no more than 2
nums[++count] = nums[i];
limit++;
}
continue;
}else{ // new element
limit = 1;
nums[++count] = nums[i];
continue;
}
}
return count+1;
}
}
网友评论