zoukankan      html  css  js  c++  java
  • LeetCode--083--删除排序链表中的重复元素

    问题描述:

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

    示例 1:

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

    示例 2:

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

    方法1:(超时)

     1 class Solution(object):
     2     def deleteDuplicates(self, head):
     3         """
     4         :type head: ListNode
     5         :rtype: ListNode
     6         """
     7         
     8         p = head
     9         if p == None or p.next == None:
    10             return head
    11         while p.next != None:
    12             q = p.next
    13             if p.val == q.val:
    14                 q = q.next
    15             else:
    16                 p.next = q
    17                 p = q
    18         return head

    方法2:

     1 class Solution(object):
     2     def deleteDuplicates(self, head):
     3         """
     4         :type head: ListNode
     5         :rtype: ListNode
     6         """
     7         
     8         p = head
     9         if p == None or p.next == None:
    10             return head
    11         while p.next != None:
    12             q = p.next
    13             if p.val == q.val:
    14                 p.next = q.next
    15             else:
    16                 p = p.next
    17         return head

    同上:

     1 class Solution(object):
     2     def deleteDuplicates(self, head):
     3         """
     4         :type head: ListNode
     5         :rtype: ListNode
     6         """
     7         #此为不带头结点的链表
     8         if head is None:#链表为空
     9             return head
    10         cur=head
    11         while cur.next:#下一节点不为空
    12             if cur.val==cur.next.val:#第一次判断,头元素与头元素下一节点的值是否相等。。。
    13                 cur.next=cur.next.next
    14             else:
    15                 cur=cur.next
    16         return head

    方法2:

     1 class Solution(object):
     2     def deleteDuplicates(self, head):
     3         """
     4         :type head: ListNode
     5         :rtype: ListNode
     6         """
     7         a=[]
     8         l=head
     9         while l:
    10             if l.val in a:
    11                 p.next=l.next
    12             else:
    13                 a.append(l.val)
    14                 p=l
    15             l=l.next
    16         return head

    2018-07-25 13:08:38

  • 相关阅读:
    小程序开发 access_token 统一管理
    python操作mysql
    Mac版本的idea非正常关闭后,idea打开项目大面积报红
    PySpider爬取去哪儿攻略数据项目
    Python3.9安装PySpider步骤及问题解决
    Selenium 自动化测试工具
    Python 抓取猫眼电影排行
    Python爬虫基本库
    Python 创建一个Django项目
    Python 数据可视化
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/9365404.html
Copyright © 2011-2022 走看看