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.
Remove Duplicates from Sorted Array II (allow duplicates up to 2):
public class Solution {
public int removeDuplicates(int[] nums) {
int i = 0;
for (int n : nums){
if (i < 2 || n > nums[i - 2]){
nums[i] = n;
i++;
}
}
return i;
}
}
Remove Duplicates from Sorted Array(no duplicates) :
public int removeDuplicates(int[] nums) {
int i = 0;
for(int n : nums)
if(i < 1 || n > nums[i - 1])
nums[i++] = n;
return i;
}
本文介绍了一种算法,该算法可以在一个已排序的数组中移除多余的重复元素,并允许每个元素最多出现两次。提供了两种不同的实现方式:一种允许元素重复最多两次,另一种则完全移除所有重复元素。

201

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



