题目
存在一个按升序排列的链表,给你这个链表的头节点
head
,请你删除所有重复的元素,使每个元素 只出现一次 。返回同样按升序排列的结果链表。
我的题解
在原有链表基础上删除。定义两个指针l、r进行遍历和比大小。
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if head==None:
return None
l,r=head,head.next
while l!=r:
if r==None:
return head
if r.val==l.val:
l.next=r.next
r=r.next
else:
r=r.next
l=l.next
Accepted
- 166/166 cases passed (28 ms)
- Your runtime beats 98.82 % of python3 submissions
- Your memory usage beats 40.81 % of python3 submissions (15 MB)
官方题解
同样也是一次遍历的思路。
对比一下代码。区别只在于单指针和双指针。单指针因为在比大小的时候,多次重复遍历,时间更长。
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head:
return head
cur = head
while cur.next:
if cur.val == cur.next.val:
cur.next = cur.next.next
else:
cur = cur.next
return head
Accepted
- 166/166 cases passed (40 ms)
- Your runtime beats 58.09 % of python3 submissions
- Your memory usage beats 6.93 % of python3 submissions (15.1 MB)
总结
1. 链表题优先使用快慢指针。
2. 尝试过把 r=r.next 放在if else 结束后的公共区域,结果耗时更久。