[数组]80. Remove Duplicates from Sorted Array II

80. Remove Duplicates from Sorted Array II

紧接着26题,同样是移除重复的元素,但是可以允许最多两次重复元素存在。
仍然是27题的思路,但是需要一个计数器来记录重复的次数,如果重复次数大于等于2,按照27题的方式处理,如果不是重复元素,将计数器清零。

在nums新的长度以后留下的数字并没有关系。 比如长度为2,则nums[2]及以后的并不重要

JAVA 2ms

class Solution {
    public int removeDuplicates(int[] nums) {
        if(nums.length <= 2) return nums.length;
        int limit = 1;
        int count = 0;
        for(int i = 1; i<nums.length; i++){
            if(nums[i] == nums[count]){
                if(limit < 2){ // duplicated, but no more than 2
                    nums[++count] = nums[i];
                    limit++;   
                }
                continue;
                
            }else{ // new element
                limit = 1;
                nums[++count] = nums[i];
                continue;
                
            }
        }
        return count+1;
        
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容