[Leedcode] [JAVA] [876 questions] [speed pointer]

【Problem Description】

给定一个带有头结点 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,我们返回第二个结点。
 

[Thinking] answer

1. The speed of the analog time complexity: complexity of O (N) space: O (1)
class Solution {
   public ListNode middleNode(ListNode head) {
           ListNode slow=head;
           ListNode fast=head;
           while(fast!= null && fast.next!=null)
           {
//快指针q每次走2步,慢指针p每次走1步,当q走到末尾时p正好走到中间。
               slow=slow.next;
               fast = fast.next.next;
           }
           return slow;         
   }
}

###### 2. Array time complexity: O (N) space complexity: O (N)

class Solution {
    public ListNode middleNode(ListNode head) {
        ListNode[] A = new ListNode[100];
        int t = 0;
        while (head != null) {
            A[t++] = head;
            head = head.next;
        }
        return A[t / 2];
    }
}

###### 3. Single Finger time complexity: complexity of O (N) space: O (1)

class Solution {
   public ListNode middleNode(ListNode head) {
       int n = 0;
       ListNode cur = head;
       while (cur != null) {
           ++n;
           cur = cur.next;
       }
       int k = 0;
       cur = head;
       while (k < n / 2) {
           ++k;
           cur = cur.next;
       }
       return cur;
   }
}

【to sum up】

  1. Brush title list to keep in mind the speed of the pointer
  2. List of low query efficiency
  3. Scratch very important topic list
Published 22 original articles · won praise 0 · Views 423

Guess you like

Origin blog.csdn.net/dadongwudi/article/details/105059858