// 演算法與 C 版完全相同：兩個指針，k 為寫入位置，逐一檢查 nums[i] 是否與 nums[k-2] 相同。
// Algorithm identical to the C version: two pointers, k as write index, compare with nums[k-2].
// 用 std::vector<int>& 接收參數；vector 是 C++ 的動態陣列，operator[] 提供 O(1) 隨機存取。
// We take a std::vector<int>& — vector is C++'s dynamic array with O(1) indexed access via [].

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        // size() 回傳容器內元素個數，型別為 size_t（無號整數）/ size() returns element count (size_t)
        int n = static_cast<int>(nums.size());

        // k 是慢指針，代表下一個寫入位置 / k is the slow pointer = next write slot
        int k = 0;

        // range 不可變、簡單明瞭時用一般 for；此處需要索引 i，所以用傳統 for 迴圈
        // Use a classic for-loop because we need the index i (not just the value)
        for (int i = 0; i < n; i++) {
            // 同樣的判斷：前兩個直接放，之後比 nums[k-2] / same rule as C version
            if (k < 2 || nums[i] != nums[k - 2]) {
                // 寫入：vector 的 [] 與 C 陣列一樣可以直接賦值 / vector[] supports direct assignment
                nums[k] = nums[i];
                // 寫入後 k 自增 / advance k after writing
                ++k;
            }
        }

        // 回傳合法前綴長度 / return the kept prefix length
        return k;
    }
};
