`

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.

这道题目是Remove Duplicates from Sorted Array 的follow up。这里每个元素可以出现两次。我们只需要维护一个计数指针就可以了。当计数指针大于2的时候我们就需要忽略当前的元素,继续往下遍历。代码如下:
public class Solution {
    public int removeDuplicates(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        int index = 0; 
        int counter = 0;
        for(int i = 0; i < nums.length; i++) {
            if(i > 0 && nums[i] == nums[i - 1]) {
                if(counter >= 2) 
                    continue;
                else {
                    nums[index ++] = nums[i];
                    counter ++;
                }
            } else {
                nums[index ++] = nums[i];
                counter = 1;
            }
        }
        return index;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics