题目
/*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 }