【每日一题】CareerCup2.1 去除单链表的重复元素

本文探讨了如何通过使用哈希集合或双指针法去除未排序链表中的重复元素,提供了两种不同的解决方案,并详细解释了每种方法的时间复杂度。

摘要生成于 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?

 * */

分析

这道题有两问,同样都是解决单链表中重读元素的问题,不同之处在于一问可以开辟额外的内存空间而另一问不可以。

关于去重的问题我首先想到的是利用已知的数据结构特性来解决,记得以前看过一个去重的题目,大概是用哈希来解的,原因是在哈希表中数值同样的元素是对应于同一位置的,也就是说不会像数组一样允许同时存在多个重复的元素,这正是我们可以利用的地方。

如果不能开辟额外的存储空间,即不能使用哈希结构,我们只能建立两个指针,对链表中每个元素进行检验,与数组中相同,时间复杂度为O(n*n).

 

代码

 

 1 package com.careercup.chapter2;
 2 /*Write code to remove duplicates from an unsorted linked list.
 3 FOLLOW UP
 4 How would you solve this problem if a temporary buffer is not allowed?
 5  * */
 6 import java.util.HashSet;
 7 public class CareerCup_2_1 {
 8     public static void removeDuplicate(LinkNode head){
 9         HashSet<Integer> mySet = new HashSet<>();
10         mySet.add(head.getValue());
11         LinkNode current = head;
12         while(current.getNext() !=null){
13             if(mySet.contains(current.getNext().getValue())){//如果包含此元素则返回true
14                 current.setNext(current.getNext().getNext());
15             }else{
16                 mySet.add(current.getValue());
17                 current = current.getNext();
18             }
19             
20         }
21     }
22     
23     public static void removeDuplicate_NoBuffer(LinkNode head){    
24         LinkNode current =head;
25         while(current!=null){
26             LinkNode check = current;
27             while(check.getNext()!=null){
28                 if(check.getValue() == check.getNext().getValue())
29                     check.setNext(check.getNext().getNext());
30                 else 
31                     check.setNext(check.getNext().getNext());
32                 }
33             current = current.getNext();
34             }
35         }
36     }

 

 

 

转载于:https://www.cnblogs.com/sayary/archive/2013/03/04/2942978.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值