Given the head of a linked list, find all the values that appear more than once in the list and delete the nodes that have any of those values.
Return the linked list after the deletions.
Example 1:
Input: head = [1,2,3,2]
Output: [1,3]
Explanation: 2 appears twice in the linked list, so all 2's should be deleted. After deleting all 2's, we are left with [1,3].
Example 2:
Input: head = [2,1,1,2]
Output: []
Explanation: 2 and 1 both appear twice. All the elements should be deleted.
Example 3:
Input: head = [3,2,2,1,3,2,4]
Output: [1,4]
Explanation: 3 appears twice and 2 appears three times. After deleting all 3's and 2's, we are left with [1,4].
Constraints:
The number of nodes in the list is in the range [1, 105]
1 <= Node.val <= 105
Solutions
Solution 1: Hash Table
We can use a hash table $cnt$ to count the number of occurrences of each element in the linked list, and then traverse the linked list to delete elements that appear more than once.
The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the linked list.
1 2 3 4 5 6 7 8 9101112131415161718192021
# Definition for singly-linked list.# class ListNode:# def __init__(self, val=0, next=None):# self.val = val# self.next = nextclassSolution:defdeleteDuplicatesUnsorted(self,head:ListNode)->ListNode:cnt=Counter()cur=headwhilecur:cnt[cur.val]+=1cur=cur.nextdummy=ListNode(0,head)pre,cur=dummy,headwhilecur:ifcnt[cur.val]>1:pre.next=cur.nextelse:pre=curcur=cur.nextreturndummy.next
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */funcdeleteDuplicatesUnsorted(head*ListNode)*ListNode{cnt:=map[int]int{}forcur:=head;cur!=nil;cur=cur.Next{cnt[cur.Val]++}dummy:=&ListNode{0,head}forpre,cur:=dummy,head;cur!=nil;cur=cur.Next{ifcnt[cur.Val]>1{pre.Next=cur.Next}else{pre=cur}}returndummy.Next}