leetcode 26. Remove Duplicates f

2017-12-28  本文已影响0人  咿呀咿呀呦__

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.
class Solution:    
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if nums == []:
            return 0

        newTail = 0

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

        return newTail + 1

Complexity analysis:

Time complextiy : O(n). Assume that n is the length of array. Each of i and j traverses at most n steps.

Space complexity : O(1).

上一篇下一篇

猜你喜欢

热点阅读