2.1 题目:
移除未排序链表中的重复结点
进阶:
不使用额外的数据结构
解法:
使用额外数据结构的解法:
遍历链表,如果不存在该key,使用map存储 key为node.item;value为true的数据,如果存在该key则删除该结点
- public static <E> void deleteDuplicateNode1(Node<E> head){
- HashMap<E,Boolean> map = new HashMap<>();
- Node<E> current = head;
- Node<E> previous = null;
- while(current != null){
- if(map.containsKey(current.item)){
- previous.next = current.next;
- }
- else{
- map.put(current.item, true);
- previous = current;
- }
- current = current.next;
- }
- }
不使用额外数据结构的解法:
- public static <E> void deleteDuplicateNode2(Node<E> head){
- Node<E> current = head;
- while(current.next != null){
- Node<E> runner = current.next;
- do{
- if(runner.item == current.item){
- current.next = runner.next;
- }
- }while((runner = runner.next) != null);
- current = current.next;
- }
- }
Node的定义:
- public static class Node<E>{
- private E item;
- private Node<E> next;
- public Node(E item) {
- this.item = item;
- }
- public E getItem() {
- return item;
- }
- public void setItem(E item) {
- this.item = item;
- }
- public Node<E> getNext() {
- return next;
- }
- public void setNext(Node<E> next) {
- this.next = next;
- }
- }
测试用例:
构建了一个两组 0到99999
其中还对比了两个算法所用时间
在200000个数据情况下,第一种算法时间复杂度O(N) 耗时35ms 第二种算法时间复杂度O(N^2) 耗时15159ms,差距极大。
- @Test
- public void test_2_1() {
- Node<Integer> head = new Node<Integer>(0);
- Node<Integer> p = head;
- Node<Integer> node ;
- for(int i = 1;i < 200000;i++){
- if(i<100000){
- p.setNext(new Node<Integer>(i));
- }
- else{
- p.setNext(new Node<Integer>(i%100000));
- }
- p = p.getNext();
- }
- printNodeList(head);
- long start = System.currentTimeMillis();
- //LinkedListUtil.deleteDuplicateNode1(head);
- LinkedListUtil.deleteDuplicateNode2(head);
- long end = System.currentTimeMillis();
- System.out.println("time is " + (end - start));
- System.out.println("------------------------------");
- printNodeList(head);
- }
- private <E> void printNodeList(Node<E> head){
- Node<E> node = head;
- while(node != null){
- System.out.println(node.getItem());
- node = node.getNext();
- }
- }