3217 - Delete Nodes From Linked List Present in Array
C++
class Solution {
public:
ListNode* modifiedList(vector<int>& nums, ListNode* head) {
unordered_set<int> s(nums.begin(), nums.end());
ListNode* dummy = new ListNode(0, head);
for (ListNode* pre = dummy; pre->next;) {
if (s.count(pre->next->val)) {
pre->next = pre->next->next;
} else {
pre = pre->next;
}
}
return dummy->next;
}
};JAVA
class Solution {
public ListNode modifiedList(int[] nums, ListNode head) {
Set<Integer> s = new HashSet<>();
for (int x : nums) {
s.add(x);
}
ListNode dummy = new ListNode(0, head);
for (ListNode pre = dummy; pre.next != null;) {
if (s.contains(pre.next.val)) {
pre.next = pre.next.next;
} else {
pre = pre.next;
}
}
return dummy.next;
}
}
Comments
Post a Comment