26. Remove Duplicates from Sorted Array,在有序数组中去重

Last Updated: 2023-11-09 09:14:14 Thursday

-- TOC --

题目分析

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums. Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:

原地修改sorted array!可以修改输入array的长度,外围的判定代码,只关心前k个值。

Example 1:
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the returned k (hence they are underscores).

Example 2:
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores).

Constraints:

此题关键就是要避免移动array内的元素,这个操作很慢。

Python

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        a = [nums[0]]
        i = 1
        while i < len(nums):
            if nums[i] != nums[i-1]:
                a.append(nums[i])
            i += 1
        k = len(a)
        nums[:k] = a
        return k

如果用set对象去重,代码只需要4行,但内在的逻辑并不是最优的。

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        a = sorted(tuple(set(nums)))
        k = len(a)
        nums[:k] = a
        return k

完全不使用更多的内存也可以:

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        n = len(nums)
        i = 0
        j = 1
        while j < n:
            if nums[j] == nums[i]:
                j += 1
                continue
            i += 1
            if i != j:
                nums[i] = nums[j]
            j += 1
        return i + 1

C++

class Solution {
public:
    int removeDuplicates(vector<int>& nums) noexcept{
        size_t n { nums.size() };
        size_t i{};
        size_t j{1};
        while(j < n){
            if(nums[j] == nums[i]){
                ++j;
                continue;
            }
            ++i;
            if(i != j)
                nums[i] = nums[j];
            ++j;
        }
        return i+1;
    }
};

C

int removeDuplicates(int* nums, int numsSize) {
    int i=0, j=1;
    while(j < numsSize){
        if(nums[j] == nums[i]){
            ++j;
            continue;
        }
        ++i;
        if(i != j)
            nums[i] = nums[j];
        ++j;
    }
    return i+1;
}

本文链接:https://cs.pynote.net/ag/leetcode/202311071/

-- EOF --

-- MORE --