Sponsored
Sponsored
This approach uses a set for fast lookup of values that need to be removed from the linked list. By iterating through the linked list and checking if each node's value is in the set, we can efficiently determine which nodes to skip and which to keep.
Time Complexity: O(N + M), where N is the length of the linked list and M is the size of nums.
Space Complexity: O(M), where M is the size of nums.
1using System;
2using System.Collections.Generic;
3
4public class ListNode {
5 public int val;
6 public ListNode next;
7 public ListNode(int x) { val = x; }
8}
9
10public class Solution {
11 public ListNode DeleteNodes(ListNode head, int[] nums) {
12 HashSet<int> set = new HashSet<int>(nums);
13 ListNode dummy = new ListNode(0) { next = head };
14 ListNode prev = dummy, curr = head;
15
16 while (curr != null) {
17 if (set.Contains(curr.val)) {
18 prev.next = curr.next;
19 } else {
20 prev = curr;
21 }
22 curr = curr.next;
23 }
24 return dummy.next;
25 }
26}
C# uses a HashSet
for element presence checking. The approach involves pointer management with a dummy node which aids in modifying the linked list as we traverse it.
This approach leverages a two-pointer technique where the result is constructed in-place. Although it doesn't require extra storage for the set, it does involve modifications that make subsequent operations more complex in favor of reducing space usage.
Time Complexity: O(N * M), where N is the length of the linked list and M is the size of nums.
Space Complexity: O(1).
JavaScript's solution checks membership directly using includes
on the array, maintaining a straightforward approach without additional memory structures beyond what's necessary for list traversal.