【LeetCode 384】Shuffle an Array (C++)

题目描述:

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();

题目大意:

洗牌。

思路:

从最后一张牌开始确定,把当前牌和前面任意一张牌交换。
有点疑惑这是否是所有排列等概率返回的解法。

代码:

class Solution {
    vector<int> orgi, data;

public:
    Solution(vector<int> nums) {
        data = nums;
        orgi = nums;
    }

    /** Resets the array to its original configuration and return it. */
    vector<int> reset() {
        data = orgi;
        return data;
    }

    /** Returns a random shuffling of the array. */
    vector<int> shuffle() {
        int len = orgi.size();
        for (int i=len-1; i>=0; --i) {
            swap(data[i], data[rand()%(i+1)]);
        }
        return data;
    }
};

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/87110872