关键词:洗牌,随机打乱数组
1. 题目
打乱一个没有重复元素的数组。
示例:
// 以数字集合 1, 2 和 3 初始化数组。
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。
solution.shuffle();
// 重设数组到它的初始状态[1,2,3]。
solution.reset();
// 随机返回数组[1,2,3]打乱后的结果。
solution.shuffle();
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shuffle-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解法
经典的洗牌算法,思路是在前n-1张牌洗好的情况下,第n张牌随机与前n-1张牌的其中一张牌交换,或者不换。
class Solution {
public:
Solution(vector<int>& nums) {
Elements = nums;//这里的Element是全局变量
}
/** Resets the array to its original configuration and return it. */
vector<int> reset() {
return Elements;
}
/** Returns a random shuffling of the array. */
vector<int> shuffle() {
vector<int> vShuffle = Elements;
for (int i = 1; i < vShuffle.size(); ++i)//对于每个位于i的元素都交换了一次位置
{
int r = rand() % (i + 1);//r为0-i的随机数
if (r != i)
{
swap(vShuffle[r], vShuffle[i]);//交换位置
}
}
return vShuffle;
}
private:
vector<int> Elements; //定义为全局变量了
};
/**
* 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();
*/