leetcode_26. 删除排序数组中的重复项python

算法思想:

1.这里需要使用两个标记指针来确定比较的位置和插入的位置,使用的不是删除元素,而是覆盖掉重复的元素。
2.使用pre_index这个参数来标记上一个已经覆盖掉的位置,使用index这个参数来遍历这个数组,比较nums[index]和nums[pre_index]的值是否相同,相同的话,index += 1否则pre_index + = 1 nums[pre_index] = nums[index],这样就完成了最基本的覆盖操作

代码:

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
      
        if len(nums) == 0:
            return 0
        pre_index = 0
        for index, num in enumerate(nums):
            if num == nums[pre_index]:
                continue
            else:
                pre_index += 1
                nums[pre_index] = num
        return pre_index + 1

知识点enumerate

1.巧妙地使用了enumerate这个函数
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
用法

>>>seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
... print i, element
...
0 one
1 two
2 three

猜你喜欢

转载自blog.csdn.net/qq_37002901/article/details/87912136
今日推荐