Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

leetcode 142.环形链表II #37

Open
webVueBlog opened this issue May 29, 2022 · 1 comment
Open

leetcode 142.环形链表II #37

webVueBlog opened this issue May 29, 2022 · 1 comment

Comments

@webVueBlog
Copy link
Member

image
142. 环形链表 II

@webVueBlog
Copy link
Member Author

142. 环形链表 II

/*
 * @lc app=leetcode.cn id=142 lang=javascript
 *
 * [142] 环形链表 II
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} head
 * @return {ListNode}
返回入环点的位置
 * 2(x+y) = x+2y+z
 * x = z 
(72 ms)
 */
var detectCycle = function(head) {
    if (!head || head.next === null) return null
    let p = q = head
    do {
        p = p.next
        q = q.next.next
    } while (p !== q && q && q.next)

    if (p !== q) return null
    p = head
    while (p !== q) {
        p = p.next
        q = q.next
    }
    return p
};
// @lc code=end

// var detectCycle = function(head) {
//     if (!head || head.next === null) return null

//     const map = new Map()
//     let p = head
//     while (p) {
//         if (!map.has(p)) {
//             map.set(p, p)
//             p = p.next
//         } else {
//             return p
//         }
//     }
//     return false
// };

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant