// 演算法與 C 版完全相同：雙指針一次掃描。
// Same algorithm as the C version: single-pass two pointers.
// 時間 O(n)、空間 O(1)。 / Time O(n), space O(1).

#include <vector>  // 引入 std::vector。 / Bring in std::vector.
using std::vector; // 讓我們可以直接寫 vector 而不是 std::vector。 / Alias for brevity.

class Solution {
public:
    // vector<int>& nums：以「參考」傳入，不複製整個 vector，函式內的修改對外可見。
    // vector<int>& nums: pass by reference — no copy, and changes are visible to the caller.
    int removeElement(vector<int>& nums, int val) {
        int k = 0;  // k = 下一個寫入位置 / k is the next write slot.

        // 範圍 for 迴圈：x 依序拿到 nums 的每個元素 (只讀)。
        // Range-based for loop: x takes each element of nums in order (read-only here).
        // 注意：我們只用 x 來讀取，寫回 nums 時還是用索引 k。
        // We use x only for reading; writing still uses index k.
        for (int x : nums) {
            if (x != val) {       // 保留不等於 val 的元素。 / Keep elements != val.
                nums[k] = x;      // 寫到 nums[k]。因為 k <= 當前讀的位置，安全。
                                  // Write to nums[k]; safe because k never overtakes the reader.
                k++;              // 寫指針前進。 / Advance the write pointer.
            }
        }

        return k;  // 回傳保留的元素個數。 / Return the count of kept elements.
    }
};
