LeetCode算法笔记-Array组-Remove Duplicates from Sorted Array(Python版)

Description:

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.

Translate:

给定一个有序数组,删除重复内容,使每个元素只出现一次,并返回新的长度。
不要为其他数组分配额外的空间,你必须在O(1)的空间里完成这个功能。

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.

Solution:

class Solution:
    # @param a list of integers
    # @return an integer
    def removeDuplicates(self, A):
        if not A:
            return 0

        newTail = 0

        for i in range(1, len(A)):
            if A[i] != A[newTail]:
                newTail += 1
                A[newTail] = A[i]

        return newTail + 1

by https://leetcode.com/problems/remove-duplicates-from-sorted-array/discuss/11751

Analysis:

LeetCode算法笔记-Array组-Remove Duplicates from Sorted Array(Python版)_第1张图片

本题主要是运用一个数指向第一个重复数,然后把第二个重复数与与这个数不一样的数交换,并指向这个数,继续往后比较。

你可能感兴趣的:(LeetCode算法笔记-Array组-Remove Duplicates from Sorted Array(Python版))