Remove Duplicate from Unsorted List

之前介绍过在排好序的链表中删除节点,只需要遍历一遍链表,所以时间复杂度为O(n)。这篇文章讨论对无序链表的去重问题。

给定一个无序链表,删除里面的重复元素,我们用bruce force来进行的话时间复杂度为O(n^2),我们从头节点开始判断,如果有相等的元素,就将当前节点的next指向下一个节点的next。每个元素都要遍历一次它们后面的元素。代码如下:

public ListNode deleteDuplicates(ListNode head) {
if(head == null) return head;
ListNode current = head;
while(current != null) {
int value = current.val;
ListNode find = current;
while(find.next != null) {
if(find.next == value) {
find.next = find.next.next;
} else {
find = find.next;
}
}
current = current.next;
}
return head;
}


我们也可以先用归并排序将链表排序,然后在去重,这样事件复杂度为O(n + nlogn), 也就是O(nlogn)。代码如下:

public class DeleteDuplicate {
public ListNode deleteDupli(ListNode head) {
if(head == null) return null;

ListNode helper = sort(head);
while(head.next != null) {
if(head.val == head.next.val) {
head.next = head.next.next;
} else {
head = head.next;
}
}
return helper;
}

public ListNode sort(ListNode head) {
if(head == null || head.next == null) return head;
ListNode fast = head;
ListNode slow = head;
while(fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
ListNode next = slow.next;
slow.next = null;
ListNode a = sort(next);
ListNode b = sort(head);
return merge(a, b);
}

public ListNode merge(ListNode a, ListNode b) {
if(a == null) return b;
if(b == null) return a;

if(a.val > b.val){
b.next = merge(a, b.next);
return b;
} else {
a.next= merge(a.next, b);
return a;
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值