Array - 80. Remove Duplicates from Sorted Array II

时间:2022-07-25
本文章向大家介绍Array - 80. Remove Duplicates from Sorted Array II,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

80、Remove Duplicates from Sorted Array II 相似题型: 26

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.

Example 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.

思路:

这一题的做法和26题可以说是一模一样,也是用两个指针,一个遍历数组,一个记录新数组长度位置,这一题比26题多的是在于要保留两个重复的数。

代码:

java:

class Solution {

    public int removeDuplicates(int[] nums) {
        if (nums == null || nums.length <= 2) return nums.length;
        
        int res = 2;
        for (int i = 2; i < nums.length; i++) {
            if (!(nums[res-1] == nums[res-2] && nums[res-1] == nums[i])) {
                nums[res++] = nums[i];
            }
        }
        
        return res;
    }
}

go:

func removeDuplicates(nums []int) int {

    if nums == nil || len(nums) <= 2 {
        return len(nums)
    }
    
    cnt := 2
    for i:= 2; i < len(nums); i++{
        if !(nums[cnt-1] == nums[cnt-2] && nums[cnt-1] == nums[i]) {
            nums[cnt] = nums[i]
            cnt++
        }
    }
    
    return cnt
}