Leetcode23

Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 1->2->3

第一想法是转 list 再转链表

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        s = []
        while head:
            if head.val not in s:
                s.append(head.val)
            head = head.next
        
        dummy = current = ListNode(None)
        for i in s:
            current.next = ListNode(i)
            current = current.next
        
        return dummy.next

回头再审下题,给了一个排好序的链表,这题考的操作链表的能力

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        current = head
        
        while current is not None and current.next is not None:
            if current.val == current.next.val:
                current.next = current.next.next
            else:
                current = current.next
            
        return head

考虑清楚后再动手,比较快,着急只会起反作用

duplicate

难度降低后快了很多,可是成就感低了很多

慢就是快


Recent posts

Leetcode30

ElasticSearch 系列(一)

Mysql 分区表实践

Kafka 入门

Hugo 安装


Related posts

Leetcode30

Leetcode29

Leetcode28

Leetcode27

Leetcode26

Leetcode25

Leetcode24


Archives

2020 (11)
2019 (56)