Re: [闲聊] 每日leetcode

楼主: argorok (s.green)   2024-09-06 08:55:07
https://leetcode.com/problems/delete-nodes-from-linked-list-present-in-array/
3217. Delete Nodes From Linked List Present in Array
要删掉linked list里值跟array元素一样的node
思路:
先把nums转成set
再traverse list查set看node是不是要删
最后回传改完的head
C++ code:
class Solution {
public:
ListNode* modifiedList(vector<int>& nums, ListNode* head) {
ListNode *dummy = new ListNode(0, head);
ListNode *prev = dummy, *cur = head;
unordered_set<int> set;
for(auto n : nums){
set.insert(n);
}
while(cur != nullptr){
if(set.count(cur->val)){
prev->next = cur->next;
delete cur;
cur = prev->next;
} else {
prev = cur;
cur = cur->next;
}
}
ListNode *ans = dummy->next;
delete dummy;
return ans;
}
};

Links booklink

Contact Us: admin [ a t ] ucptt.com