移除數組中的重複元素

移除數組中的重複元素

Remove Duplicates from 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.

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.

思路

  1. 簡單到爆,思路不寫

代碼

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        idx = 0
        for i in range(len(nums)):
            if nums[idx] != nums[i]:
                idx += 1
                nums[idx] = nums[i]
        return idx + 1

本題以及其它leetcode題目代碼github地址: github地址

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