1.借助hash记录,时间
O
(
n
)
O(n)
O(n),空间
O
(
n
)
O(n)
O(n)
class Solution {
public:
map<int,int>M;
ListNode*deleteDuplication(ListNode* pHead){if(!pHead)return nullptr;
ListNode* pre = pHead;
ListNode* p = pHead;while(p){
M[p->val]++;
p = p->next;}
p = pHead;//从头开始//开头就重复while(p&&M[p->val]!=1){
pre = p;
p = p->next;}
pHead = p;//非开头重复while(p){if(M[p->val]!=1){
pre->next = p->next;
p=pre->next;continue;}
pre = p;
p = p->next;}return pHead;}};
2.需要一个辅助节点,时间
O
(
n
)
O(n)
O(n),空间
O
(
1
)
O(1)
O(1)
class Solution {
public:
ListNode*deleteDuplication(ListNode* pHead){
ListNode* p = new ListNode(0);//新建的节点
ListNode* new_head = p;
ListNode* q = pHead;while(q){while(q&&q->next&&q->val == q->next->val){//检测连续元素相等,例如1,1,2,2,3,4最后跳到3int temp = q->val;while(q&&q->val==temp)//跳过连续相等元素{
q = q->next;}}
p->next = q;
p = p->next;if(q)
q = q->next;}return new_head->next;//去除新建的节点}};