Featured image of post Remove Duplicate Node

Remove Duplicate Node

移除重复节点

分析

  1. 使用一个哈希集合 hash 来存储链表中已经出现的数值
  2. 用两个指针:
    • pre:当前保留的最后一个节点;
    • cur:正在检查的下一个节点;
  3. 如果 cur->val 已经在 hash 中出现过,说明是重复节点:
    • pre->next 指向 cur->next,跳过当前节点
  4. 否则:
    • 将该值加入 hash,并正常前进两个指针;
  5. 遍历完整个链表后返回 head

时间复杂度

时间复杂度 O(n)

空间复杂度

空间复杂度为 O(n)

C++代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution
{
public:
    ListNode* removeDuplicateNodes(ListNode* head)
    {
        if (!head || !head->next)
            return head;  // 空链表或单节点链表直接返回

        ListNode *pre = head, *cur = head->next;
        std::unordered_set<int> hash;
        hash.insert(pre->val);  // 将头结点的值加入哈希集合

        while (cur)
        {
            if (hash.count(cur->val))  // 当前节点值已出现,跳过该节点
            {
                pre->next = cur->next;
                cur = pre->next;
            }
            else  // 新值,保留该节点
            {
                hash.insert(cur->val);
                pre = cur;
                cur = cur->next;
            }
        }

        return head;
    }
};
Built with Hugo
Theme Stack designed by Jimmy