当前位置 : 主页 > 手机开发 > ROM >

26. Remove Duplicates from Sorted Array

来源:互联网 收集:自由互联 发布时间:2021-06-10
Given a sorted array nums , remove the duplicatesin-placesuch that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this bymodifying the input arrayin-placewith O(1) extra m

Given a sorted array nums, 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.

My idea:use 1 pointer to search

 

class Solution:
    def removeDuplicates(self, nums):
        if(nums==[]):
            return 0
        
        a=nums[0]
        p=0
        while(p<len(nums)-1):
            while((nums[p+1]==a)):
                del nums[p+1]
                if(p+1==len(nums)):
                  break

            p=p+1
            if (p == len(nums)):
                break
            a = nums[p]
        return len(nums)
执行用时 :  104 ms, 在Remove Duplicates from Sorted Array的Python3提交中击败了50.59% 的用户 内存消耗 :  14.6 MB, 在Remove Duplicates from Sorted Array的Python3提交中击败了97.03% 的用户

思路跟前面几题差不多其实

网友评论