100. Remove Duplicates from Sorted Array

題目

https://www.lintcode.com/problem/remove-duplicates-from-sorted-array/description?_from=ladder&&fromId=2

實現

  1. 遍歷數組每個元素
  2. 如果 nums[unique_length] != nums[i],那麼先將 unique_length 向前移動一位後,再將 nums[i] 賦值到 nums[unique_length]
  3. 最後返回 unique + 1

代碼

class Solution:
    """
    @param: nums: An ineger array
    @return: An integer
    """
    def removeDuplicates(self, nums):
        if len(nums) == 0:
            return

        unique_length = 0

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

        return unique_length + 1

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章