LeetCode 384. Shuffle an Array 题解(C++)
题目描述
- Shuffle a set of numbers without duplicates.
示例
// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
solution.shuffle();// Resets the array back to its original configuration [1,2,3].
solution.reset();// Returns the random shuffling of array [1,2,3].
solution.shuffle();
思路
- 这道题使用洗牌算法以O(n)的时间复杂度完成。对数组进行遍历,对数组内的每一个元素,都选择数组内的一个随机位置的元素与之进行交换,这里有两种方法:
- 第一种方法是每个元素都与整个数组的某个随机位置进行交换,比如nums[0]先与数组下标从0到length-1的某一随机元素进行交换(包括nums[0]本身),nums[1]也与数组下标从0到length-1的某一随机元素进行交换(同样包括本身),即随机位置randomPos = rand() % numsLength;
- 第二种方法是每个元素与其自身及其后面的某一数组随机位置元素进行交换,比如nums[0]与数组下标0到length-1的某一随机元素进行交换(包括本身),nums[1]与数组下标1到length-1的某一随机元素进行交换(包括本身),即randomPos = i + rand() % (numsLength - i)。
- 建议使用第二种,因为第一种已经被证明在n大于等于18时,每个元素随机的概率会不一样。
代码
class Solution
{
public:
Solution(vector<int> nums)
{
originalNums = nums;
shuffleNums = nums;
srand(time(0));
}
/** Resets the array to its original configuration and return it. */
vector<int> reset()
{
return originalNums;
}
/** Returns a random shuffling of the array. */
vector<int> shuffle()
{
int numsLength = shuffleNums.size();
for (int i = 0; i < numsLength; ++i)
{
//第一种洗牌算法
//int randomPos = rand() % numsLength;
//第二种洗牌算法
int randomPos = i + rand() % (numsLength - i);
swap(shuffleNums[i], shuffleNums[randomPos]);
}
return shuffleNums;
}
private:
vector<int> originalNums;
vector<int> shuffleNums;
};