温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

LeetCode中怎么删除排序链表中的重复元素

发布时间:2021-08-02 15:51:47 阅读:138 作者:Leah 栏目:大数据
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

LeetCode中怎么删除排序链表中的重复元素,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

题目描述:

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

示例 1:

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

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

 

思路分析:

这是一个简单的问题,仅测试你操作列表的结点指针的能力。由于输入的列表已排序,因此我们可以通过将结点的值与它之后的结点进行比较来确定它是否为重复结点。如果它是重复的,我们更改当前结点的 next 指针,以便它跳过下一个结点并直接指向下一个结点之后的结点。

 

复杂度分析

时间复杂度:O(n),因为列表中的每个结点都检查一次以确定它是否重复,所以总运行时间为 O(n),其中 n 是列表中的结点数。

空间复杂度:O(1),没有使用额外的空间。

 

Python实现

# Definition for singly-linked list.# class ListNode:#     def __init__(self, val=0, next=None):#         self.val = val#         self.next = nextclass Solution:    def deleteDuplicates(self, head: ListNode) -> ListNode:        # 快慢指针        if not head:            return None        fast, slow = head, head        while fast:            if fast.val != slow.val:                slow.next = fast                slow = slow.next            fast = fast.next        slow.next = None        return head
   

java实现:

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

另一个版本的实现:

class Solution {    public ListNode deleteDuplicates(ListNode head) {        if(head==null){            return head;        }        ListNode dummhead=new ListNode(0);        dummhead.next=head;        ListNode cur=head;        ListNode last=head.next;        while(last!=null){            if(cur.val==last.val){                ListNode tmp=null;                tmp=last.next;                cur.next=tmp;                last=tmp;            }else{                cur=last;                last=last.next;            }        }        return dummhead.next;    }}

看完上述内容,你们掌握LeetCode中怎么删除排序链表中的重复元素的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

原文链接:https://my.oschina.net/u/4597666/blog/4943962

AI

开发者交流群×