Remove Duplicates from Unsorted List
Solutions
Approach 1 – Using hash table
Steps
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode DeleteDuplicates(ListNode head)
{
HashSet<int> set = new HashSet<int>();
ListNode previous = null;
if (head == null) return null;
ListNode temp = head;
while (temp != null)
{
if (set.Contains(temp.val))
{
previous.next = temp.next;
}
else
{
set.Add(temp.val);
previous = temp;
}
temp = temp.next;
}
return previous;
}
}
Approach 2 – No Buffer Allowed
Steps
Last updated