leetcode 83. Remove Duplicates from Sorted List (python)

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

描述

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]
复制代码

Note:

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.
复制代码

解析

根据题意,就是给出了一个已经排好序的链表头节点 head ,要求我们取掉链表中的重复的节点,返回来的结果链表仍然是排好序的,这道题其实就是考察我们遍历链表节点和删除链表节点的基本操作,思路比较简单:

  • 从遍历链表 head
  • 如果 head 为空,直接返回 head
  • 如果 head 没有下一个节点,其本身就是没有重复节点的链表,直接返回 head
  • 初始化结果 result ,赋值为 head
  • while 循环,当 head 为真且 head.next 为真的时候,如果 head 的下一个节点和当前节点值相等,直接让当前节点直接连接到下一个节点的下一个节点,重复该过程
  • 最后直接返回 result

解答

class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head :return head
        if head and not head.next: return head
        result = head
        while head and head.next:
            if head.val == head.next.val:
                head.next = head.next.next
            else:
                head = head.next
        return result
                        	      
		
复制代码

运行结果

Runtime: 42 ms, faster than 23.95% of Python online submissions for Remove Duplicates from Sorted List.
Memory Usage: 13.7 MB, less than 13.02% of Python online submissions for Remove Duplicates from Sorted List.
复制代码

原题链接:leetcode.com/problems/re…

您的支持是我最大的动力

猜你喜欢

转载自juejin.im/post/7019496984805539847