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.
有序数组去重,每个重复元素最多保留两个。
和LeetCode 26.Remove Duplicates from Sorted Array
相识,只不过这里每个重复的元素可以保留两个。
class Solution {
public int removeDuplicates(int[] nums) {
int i,j;
for(i=2,j=2 ; i<nums.length;i++)
if(nums[j-2]!=nums[i])
nums[j++]=nums[i];
return j;
}
}
这类问题有个总结的解法 如果是可以保留重复k个元素
class Solution {
public int removeDuplicates(int[] nums,int k) {
if(nums.size()<k) return nums.size(); // if array size is less than k then return the same
int i,j;
for(i=k,j=k ; i<nums.length;i++)
if(nums[j-k]!=nums[i]) nums[j++]=nums[i];
return j;
}