80. Remove Duplicates from Sorted Array II
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.
题意:
紧接着26. Remove Duplicates from Sorted Array,只保留一个重复的元素的题,此题也是删除数组重复元素,但是重复元素最多允许出现两次。
思路:
26. Remove Duplicates from Sorted Array中只保留一个重复的元素,所以j从1开始,依次判读取的那个元素是否和j-1的元素是否相等,现在是两个重复的元素,应该j从2开始,比较j与j-1和j-2是否相等,26. Remove Duplicates from Sorted Array标志位从1开始,此题应该从2开始。
1 | class Solution { |
引申:
当可以重复3个、4个、、、、、n个呢,唯一的不同点就是标志位的选取有变换,当前元素和标志位之前元素比较各个数有变化,其他都是相同的,所以由公共的代码解法,适应任意多的重复元素个数。
1 | class Solution { |