// 演算法：用慢指針 k 當寫入位置；對每個 nums[i]，若 k<2 或 nums[i]!=nums[k-2] 就保留。
// Algorithm: slow pointer k is the write index; keep nums[i] iff k<2 or nums[i]!=nums[k-2].
// 因為陣列已排序，前面區段最多出現兩次的不變量讓 nums[k-2] 比較足以判斷重複次數。
// Because the array is sorted, comparing with nums[k-2] is enough to enforce "at most twice".

int removeDuplicates(int* nums, int numsSize) {
    // k 是下一個寫入位置，同時也是目前合法前綴的長度 / k = next write slot, also current kept length
    int k = 0;

    // 用 i 從頭掃到尾讀取每個元素 / iterate i from 0 to numsSize-1, reading each element
    for (int i = 0; i < numsSize; i++) {
        // 條件 1：前兩個元素無條件寫入（不可能違反「最多兩次」）
        // Condition 1: the first two elements are always safe to keep
        // 條件 2：若 nums[i] 與目前合法前綴倒數第二個 nums[k-2] 不同，代表此值尚未滿兩次
        // Condition 2: if nums[i] differs from nums[k-2], this value has appeared fewer than twice
        if (k < 2 || nums[i] != nums[k - 2]) {
            // 把當前元素寫入位置 k；nums[i] 是讀，nums[k] 是寫 / write nums[i] into slot k
            nums[k] = nums[i];
            // 寫入後 k 前進一格 / advance write pointer after the write
            k++;
        }
        // 若條件不成立就跳過此元素（相當於刪除）/ otherwise skip — effectively deletes this duplicate
    }

    // 回傳合法前綴的長度，即答案 k / return the length of the kept prefix
    return k;
}
