• 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

  • 相关阅读:
    C++类型转换(字符串)
    GDI+ 中Image::FromStream ,用流的方式显示图像
    mfc对话框序列化实例
    配置android开发环境eclipse获取ADT获取不到(转)
    vs开发错误总结
    MFC获取文件操作
    Android系统架构剖析(转)
    OpenCV 图像采样 插值 几何变换
    C++ char*,char[],string,CString转换
    Simscape Multibody 教程 —— 入门学习
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/9365404.html
Copyright © 2020-2023  润新知