Leetcode P80 Remove Duplicates from Sorted Array II @python Lang (LL)

时光总嘲笑我的痴心妄想 提交于 2020-01-25 09:45:23

Link: https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
Content:
在这里插入图片描述
Method: two pointers (slow and fast pointers)
Algorithm: same with P26

  1. 单独讨论长度为0,1,2的情况
  2. slow pointer从i = 1开始,fast pointer j = 2 to len(nums)
  3. if nums[j] != nums[i-1] 隔两个数比较,移动slow pointer i,将fast pointer 赋值
  4. 因为 pointers 是index,return i + 1

Code:

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) < 3:
            return len(nums)
        else:
            i = 1 #slow pointer
            for j in range(2, len(nums)): #fast pointer
                if nums[j] != nums[i-1]:
                    i += 1
                    nums[i] = nums[j]
            return i+1
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!