/*
 * Algorithm: Two pointers on two sorted arrays.
 * 演算法：對兩個已排序陣列使用雙指針。
 * Walk i through nums1 and j through nums2; on equal values return the value
 * (it must be the smallest because both arrays are sorted ascending). Otherwise
 * advance whichever pointer points to the smaller value.
 */

int getCommon(int* nums1, int nums1Size, int* nums2, int nums2Size) {
    // i, j 是兩個指針，分別指向 nums1 和 nums2 目前要比較的位置
    // i and j are the two pointers, one for each array, both starting at index 0
    int i = 0, j = 0;

    // 當兩個指針都還在陣列範圍內時繼續循環
    // Loop while neither pointer has walked off the end of its array
    while (i < nums1Size && j < nums2Size) {
        // 取出當前兩個位置的值，方便比較與閱讀
        // Cache the two current values for readability
        int a = nums1[i];   // nums1[i] 等同於 *(nums1+i) / array indexing in C
        int b = nums2[j];

        if (a == b) {
            // 第一次相等就是最小的共同值（因為兩陣列都從小到大）
            // First equality is the minimum common value (both arrays are ascending)
            return a;
        } else if (a < b) {
            // a 比 b 小：a 不可能出現在 nums2 後面（nums2 只會更大），跳過 a
            // a < b: a cannot appear later in nums2 (which only grows), so skip a
            i++;
        } else {
            // 對稱情況：b 比較小，跳過 b
            // Symmetric case: b is smaller, advance j
            j++;
        }
    }

    // 某一個指針已到底而仍未找到共同值，表示沒有共同元素
    // One array exhausted without a match — no common value exists
    return -1;
}
