美文网首页
27. Remove Element | 26. and 80.

27. Remove Element | 26. and 80.

作者: 4v3r9 | 来源:发表于2019-01-16 10:42 被阅读6次

27. Remove Element

题目描述见 https://leetcode.com/problems/remove-element/

维护两个指针,思想类似 LeetCode 283 方法三.

时间复杂度:O(n)
空间复杂度:O(1)

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        #method 1
       if not nums:
            return 
        
        p1, p2 = 0, 0
        
        while p2 < len(nums):
            if nums[p2] != val:
                nums[p1] = nums[p2]
                p1 +=1
            p2 +=1
        return p1

26. Remove Duplicates from Sorted Array

题目描述:https://leetcode.com/problems/remove-duplicates-from-sorted-array/

同样是采用两个指针的方法.

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        
        #method1
        if not nums:
            return 0
        p1, p2 = 1,1
        
        while p2 < len(nums):
            if nums[p2]!=nums[p1-1]:
                nums[p1] = nums[p2]
                p1 +=1
            p2 +=1
        return p1

80. Remove Duplicates from Sorted Array II

题目描述:https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/

同样是采用两个指针的方法.

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        
        #method 1
        if not nums:
            return 0
        if len(nums) in [1,2]:
            return len(nums)
        
        p1, p2 = 2,2
        
        while p2 < len(nums):
            if nums[p2] == nums[p1-1] and nums[p2] == nums[p1-2]:
                pass
            else:
                nums[p1] = nums[p2]
                p1 +=1
            p2 +=1
                
        return p1

相关文章

网友评论

      本文标题:27. Remove Element | 26. and 80.

      本文链接:https://www.haomeiwen.com/subject/yzbpdqtx.html