/*
 * Algorithm / 演算法：
 *   Two pointers (fast/slow) on a sorted array.
 *   k = next write slot; i scans every element.
 *   Write nums[i] into nums[k] only when it differs from nums[k-1].
 *   雙指針：k 指向下一個寫入位置，i 掃過所有元素，遇到新值才寫入。
 */

int removeDuplicates(int* nums, int numsSize) {
    // 邊界情況：空陣列直接回傳 0 / Edge case: empty array → answer is 0.
    // 題目保證 numsSize >= 1，但寫上去比較保險。
    if (numsSize == 0) return 0;

    // k 是慢指針，代表「目前已經放好的唯一元素個數」，也是下一個要寫入的位置。
    // k is the slow pointer: count of unique elements stored so far AND the next write index.
    // 第一個元素一定是唯一的，所以 k 從 1 開始（nums[0] 自己就佔一個位置）。
    // The first element is trivially unique, so start k at 1 (nums[0] is already in place).
    int k = 1;

    // i 是快指針，從索引 1 開始掃到結尾 / Fast pointer i scans from index 1 to the end.
    for (int i = 1; i < numsSize; i++) {
        // 因為陣列已排序，重複值一定相鄰；只需比較目前值和「最後保留的值」nums[k-1]。
        // Since the array is sorted, duplicates are consecutive — compare nums[i] to nums[k-1].
        if (nums[i] != nums[k - 1]) {
            // 發現新的唯一值：把它寫到 nums[k]，再讓 k 前進一格。
            // Found a new unique value: copy it to nums[k], then advance k.
            // 註：nums[i] 和 nums[k] 可能是同一格（當 k == i），這時等於什麼都沒做，仍正確。
            // Note: when k == i, this is a self-assignment — harmless and still correct.
            nums[k] = nums[i];
            k++;  // 寫入後寫入位置往右移一格 / Move the write slot one step right.
        }
        // 若 nums[i] == nums[k-1]，代表是重複，直接跳過（i 自然會在下一輪前進）。
        // Otherwise it's a duplicate — skip it; the for-loop advances i automatically.
    }

    // 回傳唯一元素的個數；nums[0..k-1] 即為去重後的結果。
    // Return the count of unique elements; nums[0..k-1] holds the deduplicated values.
    return k;
}
