[leetcode] 384. Shuffle an Array

网友投稿 279 2022-09-15

[leetcode] 384. Shuffle an Array

Description

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 {private: vector v;public: Solution(vector nums):v(nums) { } /** Resets the array to its original configuration and return it. */ vector reset() { return v; } /** Returns a random shuffling of the array. */ vector shuffle() { vector res=v; int n=v.size(); for(int i=0;i param_1 = obj.reset(); * vector param_2 = obj.shuffle(); */

参考文献

​​[leetcode] 384. Shuffle an Array 解题报告​​​​[LeetCode] Shuffle an Array 数组洗牌​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:如何从0到1搭建私域流量!
下一篇:[leetcode] 69. Sqrt(x)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~