##leetcode—80 Remove Duplicates from Sorted Array II
####题目
https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/
这道题是26#题的进阶,#26只要求剔除重复的数字,并不关心数字重复的次数。而这道题关注重复次数,如果重复次数在2次以内包括2次,则需要把数字都留在数组中;如果重复次数在2次以上,则只允许该数字重复出现两次在数组中。也要求不能增加新的数组。例子:
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.
Given nums = [0,0,1,1,1,1,2,3,3],
Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.
It doesn't matter what values are set beyond the returned length.
####思路及解法
首先维护两个指针,一个遍历原数组,另一个记录数组调整的最后位置,另外还要有一个值count来记录重复数字出现的次数,我们要用count的值来判断应该将该数字重复几次放入到数组中。
对于一个数字,他与前一个数字的关系只有两种:不相等的情况,这时这个数肯定是要放入最后的结果的,所以我们调整数组,同时要计数,也就是这个数字已经出现一次了;相等的情况,这种情况一定发生在不相等的情况后,所以对这个数字的计数已经是1了,我们循环相等的情况,但只将计数次数为2的调整数组。
####代码
class Solution {
public int removeDuplicates(int[] nums) {
int len = nums.length;
int j = 0;
int count = 1;
for(int i = 1 ; i < len ; i++){
if(nums[i] != nums[i-1]){
j++;
nums[j] = nums[i];
count = 1;
}else{
while(count<2){
count++;
j++;
nums[j] = nums[i];
}
}
}
return j+1;
}
}