LeetCode-26 - Remove Duplicates

2017-12-15  本文已影响72人  空即是色即是色即是空

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.

Solution

思路:
a. 设定两个哨兵,一个为遍历(每次一定+1)的index,一个为去重后最尾元素的index
b. 遍历的值如果遇到与去重后最尾值相等,遍历index则持续+1
c. 最后返回去重结果最尾元素的index + 1

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

        i, j = 0, 1
        
        while j < len(nums):
            while j < len(nums) and nums[j] == nums[i]:
                j += 1
            if j < len(nums):
                nums[i + 1] = nums[j]
                i += 1
                j += 1
        return i + 1
上一篇 下一篇

猜你喜欢

热点阅读