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]No.876 链表的中间结点 #32

Open
liangbus opened this issue Mar 31, 2020 · 0 comments
Open

[leetcode]No.876 链表的中间结点 #32

liangbus opened this issue Mar 31, 2020 · 0 comments
Labels

Comments

@liangbus
Copy link
Owner

  1. 链表的中间结点
    给定一个带有头结点 head 的非空单链表,返回链表的中间结点。

如果有两个中间结点,则返回第二个中间结点。

示例 1:

输入:[1,2,3,4,5]
输出:此列表中的结点 3 (序列化形式:[3,4,5])
返回的结点值为 3 。 (测评系统对该结点序列化表述是 [3,4,5])。
注意,我们返回了一个 ListNode 类型的对象 ans,这样:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.
示例 2:

输入:[1,2,3,4,5,6]
输出:此列表中的结点 4 (序列化形式:[4,5,6])
由于该列表有两个中间结点,值分别为 3 和 4,我们返回第二个结点。

其实这题不难,自己开始打开尝试做还是做出来了,只不过用的是普通遍历的方法,如下

var middleNode = function(head) {
    let curNode = head
    let size = 1
    const map = [curNode]
    while(curNode.next) {
        curNode = curNode.next
        map.push(curNode)
        size++
    }
    return map[Math.floor(size/2)]
};

时间复杂度为 O(n)

后来看了下题解,发现了另外一个很重要的思想,当时第一次看到确实感觉到很厉害啊,这都能想到

快慢指针
就是用两个指针进行遍历,快指针一次走两步,慢指针一次走一步,当快指针走到尽头的时候,慢指针肯定处在中间位置

Niubility! (仿佛打开了新世界一样,>3<)

var middleNode = function(head) {
    let fast = head
    let slow = head
    while(fast && fast.next) {
        slow = slow.next
        fast = fast.next.next
    }
    return slow
};
@liangbus liangbus added the 算法 label Apr 1, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant