算法 | Leetcode 141 環形鏈表

給定一個鏈表,判斷鏈表中是否有環。

爲了表示給定鏈表中的環,我們使用整數 pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該鏈表中沒有環。

示例 1:

輸入:head = [3,2,0,-4], pos = 1
輸出:true
解釋:鏈表中有一個環,其尾部連接到第二個節點。

示例 2:

輸入:head = [1,2], pos = 0
輸出:true
解釋:鏈表中有一個環,其尾部連接到第一個節點。

示例 3:

輸入:head = [1], pos = -1
輸出:false
解釋:鏈表中沒有環。

題解:
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
   
   //快慢雙指針法
    //   if(head==null)  return false;
    //   ListNode fast = head.next;
    //   ListNode slow = head;
    //   while(fast!=slow&&fast.next!=null){
    //       fast = fast.next.next;
    //       slow = slow.next;
    //   }
    //   return fast==slow;

    //利用哈希表查重
    HashSet<ListNode> set = new HashSet<ListNode>();
    while(head!=null){
        if(set.contains(head)){
            return true;
        }else{
            set.add(head);
        }
        head=head.next;
    }
    return false;
    //內存溢出法
    //  List<ListNode> list = new List<ListNode>();
    //  try{
    //      while(head!=null){
    //          list.add(head);
    //          head =head.next;
    //      }
    //  }
    //  catch(Exception e){
    //      return true;
    //  }
    //  return false;
        }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章