欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Leetcode 384. Shuffle an Array (python+cpp)

程序员文章站 2024-02-13 14:33:46
...

Leetcode 384. Shuffle an Array

题目

Leetcode 384. Shuffle an Array (python+cpp)

解法:Fisher-Yates Algorithm

通过调换数组位置的方式产生shuffle效果
python代码如下:
复制有问题,截图吧
Leetcode 384. Shuffle an Array (python+cpp)
C++版本如下:
注意一下rand函数的用法,见链接:https://www.cnblogs.com/yuehouse/p/10116691.html

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