从已经排好序的数组当中移除重复的数。
用两个指针,将第i个新出现的数字,放倒第i个上就好,没有特别难度。
Follow up for “Remove Duplicates”:
What if duplicates are allowed at most twice?
For example,
Given sorted array 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. It doesn’t matter what you leave beyond the new length.
Subscribe to see which companies asked this question
public class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length==0 ) return 0;
int p=0;
int last=nums[0],count=0;
for(int i=0;i<nums.length;i++){
if(nums[i]!=last){
last=nums[i];
count=0;
}
if(count<2){
nums[p]=nums[i];
p++;
count++;
}
}
return p;
}
}