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;
}
本文介绍了一种算法,用于处理有序数组中的重复元素,确保每个元素最多出现两次。通过示例说明了如何实现这一功能,并提供了可以保留指定数量重复元素的通用解决方案。
785

被折叠的 条评论
为什么被折叠?



