leetcode384——Shuffle an Array

题目大意:打乱无重复元素的数组

分析:Fisher-Yates洗牌算法。遍历数组的每个元素,将当前元素和随机选出的下标所指的元素互相交换。

代码:

class Solution {
    vector data;
public:
    Solution(vector& nums) {
        data = nums;
    }
    
    /** Resets the array to its original configuration and return it. */
    vector reset() {
        return data;
    }
    
    /** Returns a random shuffling of the array. */
    vector shuffle() {
        vector ans(data);
        for (int i = 0;i < ans.size();i++) {
            swap(ans[i], ans[rand() % (i + 1)]);
        }
        return ans;
    }
};

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

 

你可能感兴趣的:(数据结构-数组)