[LeetCode] 384. Shuffle an Array

来源:互联网 发布:安卓防沉迷软件 编辑:程序博客网 时间:2024/06/06 09:10
             [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
原创粉丝点击