LeetCode题解 -- 双指针(80)

Remove Duplicates from Sorted Array II

Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
相似题目:Remove Duplicates from Sorted Array

快慢指针

时间复杂度:O(n)
空间复杂度:O(1)

public int removeDuplicates(int[] nums) {
        int length = nums.length;
        if(length <= 1)
            return length;
        int count = 0;
        int temp = nums[0];
        int slow = 0;
        int fast = 0;
        while(fast < length){
            if(count <= 1 && nums[fast] == temp){
                nums[slow++] = nums[fast++];
                count++;
            }else if(count >= 2 && nums[fast] == temp){
                fast++;
                count++;
            }else if(nums[fast] != temp){
                count = 1;
                temp = nums[fast];
                nums[slow++] = nums[fast++];
            }
        }
      
        return slow;
    }
发布了30 篇原创文章 · 获赞 0 · 访问量 872

猜你喜欢

转载自blog.csdn.net/fantow/article/details/104698768