leetcode 面試題 02.01. 移除重複節點

【題目】面試題 02.01. 移除重複節點

83. 刪除排序鏈表中的重複元素,有序
面試題 02.01. 移除重複節點,無序

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

示例1:

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

示例2:

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

提示:
鏈表長度在[0, 20000]範圍內。
鏈表元素在[0, 20000]範圍內。
進階:
如果不得使用臨時緩衝區,該怎麼解決?

【解題思路1】Set + 雙指針

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeDuplicateNodes(ListNode head) {
        if(head == null){
            return null;
        }
        Set<Integer> set = new HashSet<>();
        ListNode pre = head;
        ListNode cur = head.next;
        set.add(pre.val);
        while(cur != null){
            if(!set.contains(cur.val)){
                set.add(cur.val);
                pre = cur;
            }else{
                pre.next = cur.next;
            }
            cur = cur.next;
        }
        return head;
    }
}

【解題思路2】遞歸

class Solution {
    private Set<Integer> set=new HashSet<>();
    public ListNode removeDuplicateNodes(ListNode head) {
        if (head==null)//說明到了鏈表尾端
            return null;
        if (!set.contains(head.val)){//這個值第一次出現
            set.add(head.val);//set中加入這個值,防止再次出現
            head.next=removeDuplicateNodes(head.next);//保留此節點,對下一個節點繼續驗證
            return head;
        }
        else{//這個值不是第一次出現

            //當前節點不要,返回對下一個節點的驗證,注意這裏返回的也是一個鏈表
            // 的一部分,返回的節點會直接掛到上次個只出現一次的節點下面。如果說
            //鏈表不爲空,呢麼一定會有至少一個節點在上面,也就是滿足過if條件的,
            //那麼根據if中的代碼,head.next就是這裏返回的。
            return removeDuplicateNodes(head.next);
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章