跳转至

26. Remove Duplicates from Sorted Array

Leetcode Array Two Pointers

题目

[Easy]

Given a sorted array, remove the duplicates in-place such that each element appear only once 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:

Given nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the new length.

中文题目

从一个有序的数组中去除重复的数字,返回处理后的数组长度。

注意点:只能用常量的额外空间, 将不重复的数字移到数组前部,剩余的部分不需要处理

例子:

输入: nums = [1, 1, 2] 输出: 2

思路

因为去重的是一个已经排好序的数组,所以有重复的数据一定在一起,遍历数组,判断当前数据是否有重复,有重复将重复的数据用后面的数据覆盖

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n = len(nums)
        if n < 2:
            return n
        count = 0
        for i in range(1, n):
            if nums[i] != nums[count]:
                count += 1
                nums[count] = nums[i]
        return count+1