题解 | #删除有序链表中重复的元素-II#
删除有序链表中重复的元素-II
https://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024
链表问题的通用思路,弄一个假的头节点,避免分出精力来处理头节点被删了
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ #include <iterator> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ ListNode* deleteDuplicates(ListNode* head) { // write code here std::array<int,2001> counters; std::fill(counters.begin(),counters.end(),0); ListNode *cur=head,*previous,*resultPrev=new ListNode(0); while(cur){ counters[cur->val+1000]++; cur=cur->next; }; cur=head,previous=resultPrev; resultPrev->next=head; while(cur){ //cout<<cur->val<<' '<<counters[cur->val+1000]<<endl; if(counters[cur->val+1000]>1){ previous->next=cur->next; //cout<<cur->val<<' '<<cur->next->val<<' '<<counters[cur->val+1000]<<endl; cur=cur->next; continue; } previous=cur; cur=cur->next; }; return resultPrev->next; } };