【Java】劍指Offer_編程題_刪除鏈表中重複的結點

題目鏈接:https://www.nowcoder.com/questionTerminal/fc533c45b73a41b0b44ccba763f866ef

題目描述
在一個排序的鏈表中,存在重複的結點,請刪除該鏈表中重複的結點,重複的結點不保留,返回鏈表頭指針。 例如,鏈表1->2->3->3->4->4->5 處理後爲 1->2->5

第一次編輯代碼:

/*
 public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
*/
import java.util.*;
public class Solution {
    public ListNode deleteDuplication(ListNode pHead)
    {
        if(pHead == null || pHead.next == null)
            return pHead;
        HashMap<Integer,Integer> hm = new HashMap<>();
        ListNode p1 = pHead;
        while(p1 != null){
            if(hm.isEmpty()){
                hm.put(pHead.val,1);
            }else{
                if(hm.containsKey(pHead.val)){
                    hm.replace(pHead.val,hm.get(pHead.val)+1);
                }else{
                    hm.put(pHead.val,1);
                }
            }
        }
        ListNode pre = new ListNode(0);
        pre.next = pHead;
        ListNode cur = pHead;
        ListNode ans = pre;
        while(cur != null){
            if(hm.get(cur.val) > 1){
                cur = cur.next;
                pre.next = cur;
            }else{
                cur = cur.next;
                pre = pre.next;
            }
        }
        return ans.next;
    }
}

提交結果
運行超時:您的程序未能在規定時間內運行結束,請檢查是否循環有錯或算法複雜度過大。

反思
按理說只是遍歷了兩遍鏈表,算法複雜度爲O(n)纔對。
原來只需要刪除相鄰重複的就可以了。

第二次編輯代碼:

public class Solution {
    public ListNode deleteDuplication(ListNode pHead)
    {
        if(pHead == null || pHead.next == null)
            return pHead;
        ListNode head = new ListNode(-1);
        head.next = pHead;
        ListNode pre = head;
        ListNode cur = pHead;
        boolean ad = false;
        while(cur.next != null){
            if(cur.next.val == pre.next.val){
                while(cur.next!=null && cur.next.val==pre.next.val){
                    cur = cur.next; 
                }
                if(cur.next == null){
                    pre.next = null;
                }else{
                    cur = cur.next;
                    pre.next = cur;
                    if(ad == false){
                        head.next = cur;
                    }
                }
            }else{
                ad = true;
                cur = cur.next;
                pre = pre.next;
            }
        }
        return head.next;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章