面试题 02.01. 移除重复节点

题目:

面试题 02.01. 移除重复节点。

编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。

链接:https://leetcode-cn.com/problems/remove-duplicate-node-lcci/

示例:

输入:[1, 2, 3, 3, 2, 1]
输出:[1, 2, 3]

输入:[1, 1, 1, 1, 2]
输出:[1, 2]

提示:
链表长度在[0, 20000]范围内。
链表元素在[0, 20000]范围内。

进阶:如果不得使用临时缓冲区,该怎么解决?

思路:

借助哈希表。遍历链表中的节点,若该节点未出现在表中则继续遍历,若出现则删除该节点。

代码:

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

class Solution:
    def removeDuplicateNodes(self, head: ListNode) -> ListNode:
        if not head: return head
        occurred = {head.val: 1}
        pos = head
        while pos.next:
            cur = pos.next
            if not occurred.get(cur.val):
                occurred[cur.val] = 1
                pos = cur
            else:
                pos.next = pos.next.next
        return head

时间复杂度O(n),空间复杂度O(1).

你可能感兴趣的:(力扣刷题,链表,leetcode,算法)