Array - 80. Remove Duplicates from Sorted Array II

2020-09-23 17:08:54 浏览数 (4)

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.

思路:

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

代码:

java:

代码语言:javascript复制
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:

代码语言:javascript复制
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
}

1 人点赞