天天看點

141_環形連結清單

141_環形連結清單

package 連結清單;
import java.util.HashSet;
import java.util.Set;

/**
 * https://leetcode-cn.com/problems/linked-list-cycle/
 * 
 * @author Huangyujun 方法二:快慢指針法 生活常識:操場跑圈,跑得快的最終會追上跑得慢的
 */
public class _141_環形連結清單 {
    /**
     * 方法一: 使用 HashSet 實作不重複的添加 【Set 集合特點:不重複】
     * @param head
     * @return
     */
    public boolean hasCycle1(ListNode head) {
        Set<ListNode> seen = new HashSet<ListNode>();
        while (head != null) {
            if (!seen.add(head)) { // HashSet 底層是HashMap(添加元素時會判斷是否已經存在,已經存在會添加不成功)
                return true;
            }
            head = head.next;
        }
        return false;
    }


    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null)
            return false;
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast != null && fast.next != null) {
//            if(slow == fast)    return true;        //調整到後面,因為剛進來肯定是不會相等的
            slow = slow.next;
            // 等式 右邊
            // 為什麼 fast.next 不能為空,例如其為空的話 fast.next.next 就變成 null.next 報錯!
            // 為什麼 fast 不能為空,看等式左邊 fast = null 的情況
            fast = fast.next.next;
            if (slow == fast)
                return true;
        }
        return false;
    }
}