5/8 每日一題
83. Remove Duplicates from Sorted List
Easy
7.2K
246
Companies
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Example 1:

Input: head = [1,1,2] Output: [1,2]
Example 2:

Input: head = [1,1,2,3,3] Output: [1,2,3]
Constraints:
- The number of nodes in the list is in the range
[0, 300]. -100 <= Node.val <= 100- The list is guaranteed to be sorted in ascending order.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
#設定兩個快慢指針
if head == None:
return None
slow=head #讓慢指針指向head頭部,初始化慢指針
fast=head.next #快指針指向下一項
while fast:#快指針走遍一次
if slow.val == fast.val:
'''等於下一項時,不指定慢指針下一項,讓快指針跳到下一輪迴圈'''
fast=fast.next
else:
'''不相等時,讓慢指針指向該項元素,快指針在繼續往右判斷下一個元素'''
slow.next=fast
slow=slow.next
fast=fast.next
#走遍迴圈後 慢指針還沒走完,但實際上已經走到最尾巴了,所以下一項不存在
#next會指向None
slow.next=None
return head
標籤: leetcode

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁