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

  • 相关阅读:
    设置文字内容阴影效果
    android TouchEvent解析(2)
    后台运行 程序
    Intent 大全完整版
    URI URL的区别
    Java中List循环遍历的时候删除当前对象(自己)
    HDU 1005
    XML 导入 Sqlite 遇到的强大工具Navicat
    android eclipse开发环境 自动提示 程序无法响应解决方法
    DOM4J 递归解析xml文件
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/9365404.html
Copyright © 2011-2022 走看看