`

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;
        }             
     }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics