leetcode 26. Remove Duplicates from Sorted Array

題目:
  • Total Accepted: 199594
  • Total Submissions: 563740
  • Difficulty: Easy
  • Contributors: Admi

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.

思路:使用index記住當前位置,從下標1開始遍歷list,如果重複則替換index+1的位置。返回index+1.

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums)==0:return 0
        ind=0;i=1
        while i<len(nums):
            if nums[ind]!=nums[i]:
                ind+=1;nums[ind]=nums[i]
            i+=1
        return ind+1

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