LeetCode 384. Shuffle an Array 题解(C++)

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;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值