// 演算法 / Algorithm:
// 三趟線性掃描 / three linear passes into a result vector. Pass 1 collects elements
// < pivot, pass 2 collects == pivot, pass 3 collects > pivot. Relative order within
// the smaller and larger groups is preserved because we scan left-to-right.
class Solution {
public:
    vector<int> pivotArray(vector<int>& nums, int pivot) {
        // vector<int> 是會自動管理大小的動態陣列 / a dynamic array that manages its own size.
        vector<int> res;
        // 預先保留 nums.size() 空間，避免多次擴容 / reserve capacity to avoid repeated reallocation.
        res.reserve(nums.size());

        // 第一趟：收集所有小於 pivot 的元素。
        // Pass 1: collect every element strictly less than pivot.
        // range-for：x 依序取每個元素的值 / range-for: x takes each element's value in order.
        for (int x : nums) {
            if (x < pivot) {           // 只要小於的 / keep only smaller ones
                res.push_back(x);      // push_back 在尾端加一個元素 / append x to the end
            }
        }

        // 第二趟：收集所有等於 pivot 的元素。
        // Pass 2: collect every element equal to pivot (order among them is irrelevant).
        for (int x : nums) {
            if (x == pivot) {          // 只要等於的 / keep only equal ones
                res.push_back(x);      // 尾端加入（值即為 pivot）/ append it (value is pivot)
            }
        }

        // 第三趟：收集所有大於 pivot 的元素。
        // Pass 3: collect every element strictly greater than pivot.
        for (int x : nums) {
            if (x > pivot) {           // 只要大於的 / keep only larger ones
                res.push_back(x);      // 尾端加入 / append x to the end
            }
        }

        return res;                    // 回傳結果 vector / return the result vector
    }
};
