26.Remove Duplicates from Sorted Array

Tags: [sort], [pointer], [tail], [maintain_tail]

Com: {fb}

Link: https://leetcode.com/problems/remove-duplicates-from-sorted-array/\#/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 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 being1and2respectively. It doesn't matter what you leave beyond the new length.


Solution:

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

        prev = -1
        curr = 0
        tail = 0
        while curr < len(nums):
            if prev >= 0 and nums[prev] == nums[curr]:
                prev = curr
                curr += 1
                continue

            nums[tail] = nums[curr]
            prev = curr
            curr += 1
            tail += 1

        return tail

Revelation:

  • 在讨论prev是不是还指在arr外面,可以把几种讨论在脑袋里走一遍,然后有些case就可以整合到一起,然后在写code,这样code中就可以少些分散开的if statement.

Note:

  • Time complexity = O(n), n is the number of elements of the given array.
  • Space complexity = O(1).

results matching ""

    No results matching ""