题目链接: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;
}
}