LeetCode刷題系列 -- 面試題 02.01. 移除重複節點

題目

編寫代碼,移除未排序鏈表中的重複節點。保留最開始出現的節點。

示例1:

 輸入:[1, 2, 3, 3, 2, 1]
 輸出:[1, 2, 3]
示例2:

 輸入:[1, 1, 1, 1, 2]
 輸出:[1, 2]
提示:

鏈表長度在[0, 20000]範圍內。
鏈表元素在[0, 20000]範圍內。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/remove-duplicate-node-lcci
 

思路:定義兩個臨時節點 tmp1 與 tmp2 ,tmp1 爲 tmp2的上游節點。利用一個 set 用於存儲鏈表中出現過的節點

    把 head 節點存儲到 set 中,tmp2 指向 head.next ,tmp1 指向 head 

  1、如果set 包含 tmp2 節點,則 從鏈表中刪除 tmp2 節點,並將tmp2節點往下移動一位,tmp1節點不懂

   2、如果set 不包含 tmp2 節點,則 把 tmp2的值保存到 set 中將tmp1與tmp2節點往下移動一位

 

Java代碼:

    public ListNode removeDuplicateNodes(ListNode head) {
        Set<Integer>  set = new HashSet<>();
        if(head==null){
            return head;
        }
        ListNode tmp1 = head;
        ListNode tmp2 = head;
        set.add(tmp2.val);
        tmp2 = tmp2.next;
        while (tmp2!=null){
            if(set.contains(tmp2.val)){
                tmp1.next = tmp2.next;
            }else {
                set.add(tmp2.val);
                tmp1 = tmp1.next;
            }
            tmp2 = tmp2.next;

        }
        return head;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章