• 栈和队列----删除无序单链表中值重复出现的节点


    删除无序单链表中值重复出现的节点

      

      给定一个无序单链表的头节点head,删除其中值重复的节点

      例如: 1->2->3->3->4->4->2->1->1->null 删除之后变为 1->2->3->4->null

      方法1:如果链表长度为N,时间复杂度达到O(N)

      方法2:如果要求空间复杂度为O(1),应该怎样实现

      

      【解析】

      方法1:利用哈希表去实现

      使用哈希表,因为头节点是不用删除的节点,所以首先将头节点放入到哈希表中,然后从下一个节点开始遍历

      如果哈希表中已经包含下一个节点,那么就让cur的上一个存在的节点 pre pre.next = cur.next

      如果哈希表中不包含下一个节点,那么就让pre = cur

      方法2:类似选择排序的过程

      

    package com.test;
    
    import com.test.ListNode;
    
    import java.util.HashSet;
    
    /**
     * Created by Demrystv.
     */
    public class RemoveRepeat {
    
        /**
         * 方法一:利用哈希表,其时间复杂度是 O(N),空间复杂度是 O(N)
         */
        public void removeRepeat1(ListNode head){
            if (head == null){
                return;
            }
            HashSet<Integer> hashSet = new HashSet<Integer>();
            ListNode pre = head;
            ListNode cur = head.next;
            hashSet.add(head.val);
            while (cur != null){
                if (hashSet.contains(cur)){
                    pre.next = cur.next;
                }else {
                    hashSet.add(cur.val);
                    pre = cur;
                }
                cur = cur.next;
            }
        }
    
    
        // 方法二:类似选择排序的过程,时间复杂度是O(N^2),空间复杂度是O(1)
        public void removeRep2(ListNode head) {
            ListNode cur = head;
            ListNode pre = null;
            ListNode next = null;
            while (cur != null) {
                pre = cur;
                next = cur.next;
                while (next != null) {
                    if (cur.val == next.val) {
                        pre.next = next.next;
                    } else {
                        pre = next;
                    }
                    next = next.next;
                }
                cur = cur.next;
            }
        }
        
    }
  • 相关阅读:
    Python存储系统(Memcached)
    Python消息队列(RabbitMQ)
    Python的数据库操作(pymysql)
    Python档案袋(列表、元组、字典、集合 )
    Python档案袋(函数与函数装饰器 )
    EOS基础全家桶(五)钱包管理
    EOS基础全家桶(四)启动节点
    EOS基础全家桶(三)资料汇总
    EOS基础全家桶(二)安装
    EOS基础全家桶(一)开篇
  • 原文地址:https://www.cnblogs.com/Demrystv/p/9339068.html
Copyright © 2020-2023  润新知