天天看點

Leetcode141. 環形連結清單

題目傳送:​​https://leetcode.cn/problems/linked-list-cycle/​​

運作效率:

//第一種解法: 快慢指針法
public class Solution {
   public boolean hasCycle(ListNode head) {
    // 處理邊界情況
    if (head == null || head.next == null) {
      return false;
    }
    // 快慢指針
    ListNode fast = head.next;
    ListNode slow = head;
    while (fast != null && fast.next != null) {
      if (fast == slow) {
        return true;
      }
      fast = fast.next.next;
      slow = slow.next;
    }
    return false;
  }
}      
// 第二種解法: set判重     如果有環的話,那肯定會出現重複
 public boolean hasCycle(ListNode head) {
    // 處理邊界情況
    if (head == null || head.next == null) {
      return false;
    }
    HashSet<ListNode> set = new HashSet<>();
    ListNode cur=head;
    while(cur != null) {
     if(set.contains(cur)) {
       return true;
     }
     set.add(cur);
     cur = cur.next;
    }
    return false;
  }