【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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值