Remove Duplicates in Sorted Array

题目描述

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 in place with constant memory.

For example, Given input array 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.

解题方法

  • 用一个pointer表示指向新的array的下一个放置distinct value的位置
  • two pointer, p1和p2,来寻找重复的元素

Solution

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0

        newIndex = 0
        p1 = 0
        p2 = 1
        length = len(nums)

        while p1 < length:
            p2 = p1 + 1
            while p2 < length and nums[p1] == nums[p2]:
                p2 += 1
            nums[newIndex] = nums[p1]
            newIndex += 1
            p1 = p2
        return newIndex

Reference