移除链表重复节点001

1、描述

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

示例1:

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

2、关键字

链表、去重

3、思路

1、把节点存到set容器中去重(不好)
2、把节点的val值放到set中,统计set中node->next->val的个数如果等于1就说明当前节点的后边的节点已经存在了,跳过就好了

4、note

1、先插入当前节点,再统计后一个节点,
2、用set存val的值就可以达到去重的效果了,不必存放节点

5、复杂度

时间:O(N)需要遍历整个链表
空间:O(1)

6、code



/**
* 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 || !head->next) return head;  // 特判
       set<int>se;  // 用val去重
       auto tem=head;  // 存起来首节点
       while(tem&& tem->next)  // 当前节点有,后一个节点也存在的时候
       {
           se.insert(tem->val);  // 把当前节点插入se
           if(se.count(tem->next->val)==1) // 统计后一个节点的值
               tem->next=tem->next->next;
           else
               tem=tem->next;
       }
       
       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 || !head->next) return head;
        set<int>se;
        auto dmpNode = new ListNode(0);
        dmpNode->next = head;       
        //while(head){  // 这样也能过
        while(head && head->next){
            se.insert(head->val);
            while(head->next && se.count(head->next->val) == 1){
                head->next = head->next->next;
            }
            head = head->next;
        }
        return dmpNode->next;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值