1. 程式人生 > 其它 >Flask(12)- 操作 Session

Flask(12)- 操作 Session

2021-07-21 LeetCode每日一題

連結:https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/

標籤:雜湊表、連結串列、雙指標

題目

輸入兩個連結串列,找出它們的第一個公共節點。

如下面的兩個連結串列

在節點 c1 開始相交。

示例 1:

輸入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
輸出:Reference of the node with value = 8
輸入解釋:相交節點的值為 8 (注意,如果兩個列表相交則不能為 0)。從各自的表頭開始算起,連結串列 A 為 [4,1,8,4,5],連結串列 B 為 [5,0,1,8,4,5]。在 A 中,相交節點前有 2 個節點;在 B 中,相交節點前有 3 個節點。

示例 2:

輸入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
輸出:Reference of the node with value = 2
輸入解釋:相交節點的值為 2 (注意,如果兩個列表相交則不能為 0)。從各自的表頭開始算起,連結串列 A 為 [0,9,1,2,4],連結串列 B 為 [3,2,4]。在 A 中,相交節點前有 3 個節點;在 B 中,相交節點前有 1 個節點。

示例 3:

輸入:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
輸出:null
輸入解釋:從各自的表頭開始算起,連結串列 A 為 [2,6,4],連結串列 B 為 [1,5]。由於這兩個連結串列不相交,所以 intersectVal 必須為 0,而 skipA 和 skipB 可以是任意值。
解釋:這兩個連結串列不相交,因此返回 null。

注意:

  • 如果兩個連結串列沒有交點,返回 null.
  • 在返回結果後,兩個連結串列仍須保持原有的結構。
  • 可假定整個連結串列結構中沒有迴圈。
  • 程式儘量滿足 O(n) 時間複雜度,且僅用 O(1) 記憶體。

分析

如果在紙上畫一畫,就能想到一種簡單的方法(a + b = b + a)。沒想到那就樸素一點,普通迴圈。

編碼

好方法

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode A = headA, B = headB;

        // 如果兩個連結串列沒有公共節點,那麼最後都會等於null
        while (A != B) {
            // 最好的情況就是兩個連結串列長度相等
            // 兩個連結串列長度不想等的時候,短的先走完,這時候讓它從長連結串列的頭節點開始走,等長的走完後
            // 讓長的從短連結串列的頭結點開始,此時兩個節點是距離公共節點是一樣的
            A = (A == null ? headB : A.next);
            B = (B == null ? headA : B.next);
        }

        return A;
    }
}

樸素法

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode A = headA;
        while (A != null) {
            ListNode B = headB;
            while (B != null && B != A) {
                B = B.next;
            }

            if (B != null) {
                return B;
            }

            A = A.next;
        }

        return null;
    }
}