程式語言 - LeetCode - C++ - 384. Shuffle an Array



題目:


解答:

class Solution {
private:
    vector<int> org;
    vector<int> num;

public:
    Solution(vector<int>& nums) {
        this->org = nums;
        this->num = nums;
    }
    
    vector<int> reset() {
        num = org;
        return num;
    }
    
    vector<int> shuffle() {
        int n = org.size();

        for (int i = 0; i < n; ++i) {
            int j = i + (rand() % (n - i));

            swap(num[i], num[j]);
        }

        return num;
    }
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution* obj = new Solution(nums);
 * vector<int> param_1 = obj->reset();
 * vector<int> param_2 = obj->shuffle();
 */