美文网首页
[数组]80. Remove Duplicates from S

[数组]80. Remove Duplicates from S

作者: Reflection_ | 来源:发表于2018-06-13 00:11 被阅读0次

80. Remove Duplicates from Sorted Array II

给定一个有序的数组nums,删除2次以上重复内容,使每个元素只出现1/2次并返回新的长度。
不要为其他数组分配额外空间,您必须通过在O(1)额外内存中就地修改输入数组来实现此目的。

Given 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 respectively.
It doesn't matter what you leave beyond the returned length.

思路:数组有序,重复数组必定相邻!
加入一个判断是否两次的count,其它和27是一样的。

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;
        
    }
}

相关文章

网友评论

      本文标题:[数组]80. Remove Duplicates from S

      本文链接:https://www.haomeiwen.com/subject/rujdeftx.html