Cracking the coding interview--Q2.1

原文:

Write code to remove duplicates from an unsorted linked list.
FOLLOW UP
How would you solve this problem if a temporary buffer is not allowed?

译文:

删除链表中的重复元素,

另外,如果不使用临时存储空间怎么做?

解答:

如果空间没有限制,那么用一个map来标记链表中出现过的元素,然后从头到尾扫一遍链表,把出现过的删除就行了。时间复杂度O(n)。

如果限制空间,那么可以设置两个指针n、m,当n指向某个元素时,m把该元素后面与它相同的元素删除, 时间复杂度O(n2)。

import java.util.HashMap;

public class List {
    int data;
    List next;

    public List(int d) {
        this.data = d;
        this.next = null;
    }

    void appendToTail(int d) {
        List end = new List(d);
        List n = this;
        while (n.next != null) {
            n = n.next;
        }
        n.next = end;
    }

    void print() {
        List n = this;
        System.out.print("{");
        while (n != null) {
            if (n.next != null)
                System.out.print(n.data + ", ");
            else
                System.out.println(n.data + "}");
            n = n.next;
        }
    }

    void removeDuplicate() {
        HashMap<Integer, Boolean> map = new HashMap<Integer, Boolean>();
        List n = this;
        map.put(Integer.valueOf(n.data), true);
        while (n.next != null) {
            if (map.containsKey(Integer.valueOf(n.next.data))) {
                n.next = n.next.next;
            } else {
                map.put(Integer.valueOf(n.next.data), true);
                n = n.next;
            }
        }
    }

    void removeDuplicate1() {
        List n = this;
        List m;
        while (n != null) {
            m = n;
            while (m.next != null) {
                if(m.next.data == n.data)
                    m.next = m.next.next;
                else
                    m = m.next;
            }
            n = n.next;
        }
    }

    public static void main(String args[]) {
        List list = new List(0);
        list.appendToTail(1);
        list.appendToTail(2);
        list.appendToTail(2);
        list.appendToTail(3);
        list.appendToTail(3);
        list.appendToTail(4);
        list.appendToTail(1);
        list.appendToTail(2);
        list.appendToTail(0);
        list.print();
        //list.removeDuplicate();
        list.removeDuplicate1();
        list.print();
    }
}
原文地址:https://www.cnblogs.com/giraffe/p/3208212.html