题目详情
编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
示例1:
输入:[1, 2, 3, 3, 2, 1]
输出:[1, 2, 3]
示例2:
输入:[1, 1, 1, 1, 2]
输出:[1, 2]
提示:
- 链表长度在[0, 20000]范围内。
- 链表元素在[0, 20000]范围内。
进阶:
如果不得使用临时缓冲区,该怎么解决?
——题目难度:简单
/**
* 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 == NULL) return NULL;
unordered_set<int> save = {head->val};
ListNode* pos = head;
while (pos->next != NULL) {
ListNode* cur = pos->next;
if (save.count(cur->val)) {
pos->next = cur->next;
} else {
save.insert(cur->val);
pos = cur;
}
}
return head;
}
};
结果
-双重循环(快慢指针)解题代码
class Solution {
public:
ListNode* removeDuplicateNodes(ListNode* head) {
if (head == NULL) return NULL;
ListNode* fast = head;
while (fast != NULL) {
ListNode* slow = fast;
while (slow->next != NULL) {
if (slow->next->val == fast->val) {
slow->next = slow->next->next;
} else {
slow = slow->next;
}
}
fast = fast->next;
}
return head;
}
};
结果