Leetcode Remove Duplicates型別題目 (python)

努利!奮鬥!發表於2020-12-15

26. Remove Duplicates from Sorted Array

在這裡插入圖片描述

解法:two pointers

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        if not nums:
            return 0
        
        i = 0
        for j in range(1,len(nums)):
            if nums[i] != nums[j]:
                i += 1
                nums[i] = nums[j]
        
        return i+1

80. Remove Duplicates from Sorted Array II

在這裡插入圖片描述

解法:two pointers+hashmap

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        if not nums:
            return 0
        nums_dic = collections.defaultdict(int)
        nums_dic[nums[0]] += 1
        i = 0
        for j in range(1,len(nums)):
            if nums[i] != nums[j] or (nums[i]==nums[j] and nums_dic[nums[j]] < 2):
                nums_dic[nums[j]] += 1
                i += 1
                nums[i] = nums[j]
        
        return i+1

83. Remove Duplicates from Sorted List

在這裡插入圖片描述

解法

利用連結串列的特殊性,可以直接判斷相鄰元素是否重複並且跳過

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        curr = head
        while curr and curr.next:
            if curr.val != curr.next.val:
                curr = curr.next
            else:
                curr.next = curr.next.next
        
        return head

82. Remove Duplicates from Sorted List II

在這裡插入圖片描述

解法:

利用while迴圈就可以

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        dummy = ListNode(0,head)
        prev = dummy
        
        while head:
            if head.next and head.val == head.next.val:
                while head.next and head.val == head.next.val:
                    head = head.next
                prev.next = head.next
            else:
                prev = prev.next
            head = head.next
        
        return dummy.next

相關文章