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 nums =
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.Solution 1: Use p0 and p1 to store the last two numbers in order to make judgement.
public class Solution {
public int removeDuplicates(int[] nums) {
int j=0, p0=0, p1=0;
for (int i=0; i<nums.length; i++) {
if (i<2 || nums[i]!=p0 || nums[i]!=p1) nums[j++]=nums[i];
p0=p1;
p1=nums[i];
}
return j;
}
}
没有评论:
发表评论