zoukankan      html  css  js  c++  java
  • 141.Linked List Cycle---双指针

    题目链接

    题目大意:给出一个链表,判断该链表是否有环,空间复杂度最好控制在o(1)

    这个题没有给测试用例,导致没太明白题目意思,看了题解,用了两种方法示例如下:

    法一(借鉴):利用两个指针,一个指针步长为2,一个指针步长为1,若链表中有环,则两个指针同时走,在某一时刻一定会走到一起;若链表中没有环,则两个指针一定会走到null,代码如下(耗时1ms):

     1     public boolean hasCycle(ListNode head) {
     2         ListNode fast = head;
     3         ListNode slow = head;
     4         while(fast != null && slow != null && fast.next != null) {
     5             slow = slow.next;
     6             fast = fast.next.next;
     7             if(slow == fast) {
     8                 return true;
     9             }
    10         }
    11         return false;
    View Code

    法二(借鉴):利用set集合中的contains,判断是否有两个相同的结点在集合中,如果有,则有环,代码如下(耗时10ms):

     1         Set<ListNode> list = new HashSet<>();
     2         while(head != null) {
     3             if(list.contains(head)) {
     4                 return true;
     5             }
     6             else {
     7                 list.add(head);
     8                 head = head.next;
     9             }
    10         }
    11         return false;    
    View Code
  • 相关阅读:
    编程心得5
    编程心得2
    心得2
    心得1
    7-11
    7-13
    7-9
    7-8
    7-12
    7-14
  • 原文地址:https://www.cnblogs.com/cing/p/7686993.html
Copyright © 2011-2022 走看看