Cracking the coding interview--Q2.1

本文提供了一种在链表中去除重复元素的方法,并探讨了在有限空间约束下的解决方案。介绍了两种算法实现:一种利用哈希表进行去重,时间复杂度为O(n),另一种采用双指针技术,在不使用额外空间的情况下完成去重,时间复杂度为O(n²)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文:

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

 

posted on 2013-07-23 11:52 长颈鹿Giraffe 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/giraffe/p/3208212.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值