leetcode上的原题,将一个数组打乱。
洗牌算法的原理就是交换任意两个数的值。利用rand()函数生成随机index,遍历数组,与随机index交换。
代码如下:
class Solution {
private:
vector<int> nums_;
public:
Solution(vector<int> nums) {
nums_ = nums;
}
/** Resets the array to its original configuration and return it. */
vector<int> reset() {
return nums_;
}
/** Returns a random shuffling of the array. */
vector<int> shuffle() {
vector<int> num_ret;
num_ret = nums_;
int len = num_ret.size();
for(int i=0;i<len;++i)
{
int index = rand()%len;
int tmp = num_ret[i];
num_ret[i] = num_ret[index];
num_ret[index] = tmp;
}
return num_ret;
}
};