博客
关于我
L83. 删除排序链表中的重复元素
阅读量:226 次
发布时间:2019-02-28

本文共 1026 字,大约阅读时间需要 3 分钟。

在一个已排序的链表中删除重复元素,可以通过以下步骤实现:

  • 初始化指针:创建一个当前指针current指向链表的头节点,创建一个前指针prev指向一个伪头节点,用于记录前一个处理过的节点。

  • 遍历链表:使用一个循环遍历链表,直到currentcurrent.next为空。

  • 检查重复元素:在每次循环中,检查current节点的值是否与current.next节点的值相同。如果相同,跳过current.next节点,并将current指向current.next.next,这样可以跳过重复的元素。

  • 更新指针:如果没有重复元素,更新prev指针指向current,然后将current指向current.next,继续遍历下一个节点。

  • 返回结果:当遍历结束后,返回链表的头节点,因为即使头节点有重复,伪头节点的next指向正确的新链表头部。

  • 以下是实现代码:

    class Solution {    public ListNode deleteDuplicates(ListNode head) {        if (head == null) return null;        ListNode prev = new ListNode(0);        prev.next = head;        ListNode current = head;        while (current != null && current.next != null) {            if (current.val == current.next.val) {                current = current.next.next;            } else {                prev.next = current;                prev = current;                current = current.next;            }        }        return prev.next;    }}

    示例1:输入:1 -> 1 -> 2输出:1 -> 2

    示例2:输入:1 -> 1 -> 2 -> 3 -> 3输出:1 -> 2 -> 3

    这种方法使用两个指针,时间复杂度为O(n),空间复杂度为O(1),高效且节省空间。

    转载地址:http://gpvp.baihongyu.com/

    你可能感兴趣的文章
    org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
    查看>>
    org.hibernate.HibernateException: Unable to get the default Bean Validation factory
    查看>>
    org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
    查看>>
    org.tinygroup.serviceprocessor-服务处理器
    查看>>
    org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
    查看>>
    org/hibernate/validator/internal/engine
    查看>>
    SQL-36 创建一个actor_name表,将actor表中的所有first_name以及last_name导入改表。
    查看>>
    ORM sqlachemy学习
    查看>>
    Ormlite数据库
    查看>>
    orm总结
    查看>>
    os.path.join、dirname、splitext、split、makedirs、getcwd、listdir、sep等的用法
    查看>>
    os.system 在 Python 中不起作用
    查看>>
    OS2ATC2017:阿里研究员林昊畅谈操作系统创新与挑战
    查看>>
    OSCACHE介绍
    查看>>
    SQL--合计函数(Aggregate functions):avg,count,first,last,max,min,sum
    查看>>
    OSChina 周五乱弹 ——吹牛扯淡的耽误你们学习进步了
    查看>>
    SQL--mysql索引
    查看>>