141. 环形链表

141. 环形链表

题意

判断链表中是否有环;

提升:

空间复杂度为O(1)

解题思路

  • 标记链表结点是否已经访问过(通过Python的属性很容易实现);

  • 使用集合记录下访问过的结点的id;

  • 慢结点每次走一步,快结点每次走两步,如果存在环的话两者肯定会相逢(考点!!);

考察的就是第三种方法,其余的方法都是相对投机取巧的方式来实现的;

实现

class Solution(object):
   def hasCycle(self, head):
       """
      执行用时 : 76 ms, 在Linked List Cycle的Python提交中击败了9.34% 的用户
内存消耗 : 18.2 MB, 在Linked List Cycle的Python提交中击败了9.07% 的用户
      :type head: ListNode
      :rtype: bool
      """
       tmp = head
       while tmp:
           if getattr(tmp, "is_visited", False):
               return True
           tmp.is_visited = True
           tmp = tmp.next
       return False
     
   def hasCycle(self, head):
       """
      执行用时 : 64 ms, 在Linked List Cycle的Python提交中击败了14.15% 的用户
内存消耗 : 18.7 MB, 在Linked List Cycle的Python提交中击败了5.29% 的用户
      :type head: ListNode
      :rtype: bool
      """
       tmp = head
       visited_set = set()
       while tmp:
           tmp_id = id(tmp)
           if tmp_id in visited_set:
               return True

           visited_set.add(id(tmp))
           tmp = tmp.next
       return False
     
   def hasCycle(self, head):
       """
      执行用时 : 64 ms, 在Linked List Cycle的Python提交中击败了14.15% 的用户
内存消耗 : 18.1 MB, 在Linked List Cycle的Python提交中击败了9.32% 的用户
      :type head: ListNode
      :rtype: bool
      """
       if not head or not head.next:
           return False

       tmp = head
       next_tmp = head.next
       while next_tmp and next_tmp.next:
           if tmp == next_tmp:
               return True
           tmp = tmp.next
           next_tmp = next_tmp.next.next
       return False

posted @ 2019-03-25 08:30  banananana  阅读(212)  评论(0编辑  收藏  举报