面试题 02.01. [链表][哈希表]移除重复节点
面试题 02.01. 移除重复节点
方法一:缓存
这个思路很好理解,用哨兵节点遍历head,用HashSet记录节点的值,重复则跳过。
class Solution {
public ListNode removeDuplicateNodes(ListNode head) {
HashSet<Integer> hashSet = new HashSet<>();
ListNode sentinel = new ListNode(0);
sentinel.next = head;
ListNode ans = sentinel;
while(sentinel.next != null){
if(hashSet.contains(sentinel.next.val)){
sentinel.next = sentinel.next.next;
} else {
hashSet.add(sentinel.next.val);
sentinel = sentinel.next;
}
}
return ans.next;
}
}

浙公网安备 33010602011771号