【Leetcode】026-remove-duplicates-from-sorted-array

Qustion

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.

增加一个count来计数,从左至右遍历,遇到相同的直接del,否则count += 1

class Solution:
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        count = 0
        while count < len(nums)-1:
            if nums[count]==nums[count+1]:
                # The same with nums.pop(count) or nums.remove(nums[count])
                del nums[count]
            else:
                count += 1
                
        return len(nums)   
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容