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;
}
};