题目描述:
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.
移除数组中的重复元素,返回新长度。
思路:
1.two pointer方法,使用两个指针一前一后(i后,j前),初始化:i=2,j=1
2.i一直往后走,如果nums[i]不等于nums[j],或nums[i]不等nums[j-1]:nums[j]=nums[i],j往后走。
3.最后返回j+1
实现代码:public int RemoveDuplicates(int[] nums)
{
if(nums == null){
return 0;
}
var n = nums.Length;
if(n < 3){
return n;
}
var p = 1;
for(var i = 2;i < n; i++){
if(nums[i] != nums[p] || nums[i] != nums[p-1]){
p ++;
nums[p] = nums[i];
}
}
return (p + 1);
}