面试题 02.01. 移除重复节点

https://leetcode.cn/problems/remove-duplicate-node-lcci/description/

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

示例1:
输入:[1, 2, 3, 3, 2, 1] 输出:[1, 2, 3] 、
示例2:
输入:[1, 1, 1, 1, 2] 输出:[1, 2]

提示:链表长度在 [ 0 , 20000 ] [0, 20000] [0,20000] 范围内,链表元素在 [ 0 , 20000 ] [0, 20000] [0,20000] 范围内。
进阶:如果不得使用临时缓冲区,该怎么解决?

可以考慮用 雜凑表 雜凑表 雜凑表,遍歷整個鏈表,從頭結點開始。遍歷的結點為 cur

  • 若當前結點的後繼不在表中,則將當前結點的後繼插入到表中,這裏使用 countinsert 接口即可,然後再後移當前 cur
  • 若當前結點在表中,説明是重複的,就將當前結點的後繼結點與當前結點後繼的後繼相連接,cur->next = cur->next->next

當然,若鏈表頭節點 head 為空則直接返回:

if (head == nullptr) {
	return head;
}

程式如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeDuplicateNodes(ListNode* head) {
        if (head == nullptr) {
            return head;
        }

        unordered_set<int> hash = {head->val};
        struct ListNode* cur = head;
        
        while (cur->next != nullptr) {
            if (hash.count(cur->next->val) == 0) {
                hash.insert(cur->next->val);
                cur = cur->next;
            }
            else {
                cur->next = cur->next->next;
            }
        }
        cur->next = nullptr;

        return head;
    }
};

T c = O ( n ) ,   S c = O ( n ) Tc=O(n), \,Sc = O(n) Tc=O(n),Sc=O(n)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值