[leetcode] 384. Shuffle an Array 解题报告

来源:互联网 发布:程序员需要学什么语言 编辑:程序博客网 时间:2024/06/09 18:51

题目链接: https://leetcode.com/problems/shuffle-an-array/

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

思路: 在随机产生一个序列的时候, 遍历每一个元素, 并且随机一个从他开始的位置与这个位置交换, 这样任意一个元素随机到任意一个位置的概率都是1/n!.

代码如下:

class Solution {public:    Solution(vector<int> nums):vec(nums) {            }        /** Resets the array to its original configuration and return it. */    vector<int> reset() {        return vec;    }        /** Returns a random shuffling of the array. */    vector<int> shuffle() {        if(vec.size()==0) return {};        vector<int> tem(vec);        int len = vec.size();        for(int i = 0; i < len; i++)        {            int pos = rand()%(len-i);            swap(tem[i+pos], tem[i]);        }        return tem;    }private:    vector<int> vec;};/** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(nums); * vector<int> param_1 = obj.reset(); * vector<int> param_2 = obj.shuffle(); */


0 0
原创粉丝点击