[LeetCode] 384. Shuffle an Array

             [LeetCode] 384. Shuffle an Array(Medium)

Shuffle a set of numbers without duplicates.

Example: // 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();

题意与实现都不难,不过也是很经典的一类题目,shuffle问题。初次接触这类问题,想到以下几个思路:

  1. 对于第n个位置元素的选定,随机从剩下的nums.size()-n个元素中选取,直到所有位置都确定。其中用一个数组保存已选元素,另一个保存未选。时间复杂度 O(n)

  2. 对于从i=0~n的每一位,随机确定一个下标k,交换nums[i]与nums[k]的元素。 时间复杂度仍为 O(n) ,但空间复杂度降为 O(1)
    代码如下:

class Solution {
public:
    vector<int> Nums,tmp;
    Solution(vector<int> nums) {
        Nums=nums;
        tmp=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() {
        if(Nums.empty()) 
           return Nums;
        for(int i=0;i<tmp.size();i++){
            int k=rand()%tmp.size();
            int t=tmp[k];
            tmp[k]=tmp[i];
            tmp[i]=t;
        }
        return tmp;
    }
};

3.其实shuffle,就是选取数组的某一个排列。可以随机决定要进行排列的次数,再直接利用STL的排列函数next_permutation,即可得到一个shuffle。
代码如下:

class Solution {
public:
    vector<int> Nums,nums;
    Solution(vector<int> nums) {
        this->nums=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() {
        int i=rand()%(nums.size()+1);
        while(i--)
        next_permutation(nums.begin(),nums.end());
        return nums;
    }
};

PS 本题陷阱:nums可能为空,在使用随机函数rand取模确定随机数时不能为零。

另外附上一个更深入的shuffle探讨:http://www.cnblogs.com/huaping-audio/archive/2008/09/09/1287985.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值