zoukankan      html  css  js  c++  java
  • 栈和队列----删除无序单链表中值重复出现的节点

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

      

      给定一个无序单链表的头节点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;
            }
        }
        
    }
  • 相关阅读:
    聚类算法初探(六)OPTICS
    滚动视差效果——background-attachment
    Working with Strings(使用Oracle字符串)
    netstat详解
    lua的学习
    C# 基础知识 (一).概念与思想篇
    11gR2 RAC启用iptables导致节点宕机问题处理
    sqlplus中隐患组合键
    paip.vs2010 或.net 4.0安装出错解决大法.
    paip.svn使用最佳实践
  • 原文地址:https://www.cnblogs.com/Demrystv/p/9339068.html
Copyright © 2011-2022 走看看