Loading

面试题 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;
    }
}
posted @ 2020-10-22 10:40  上海井盖王  阅读(106)  评论(0)    收藏  举报