[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
- [leetcode] 384. Shuffle an Array 解题报告
- LeetCode 384. Shuffle an Array 解题报告
- [Leetcode] 384. Shuffle an Array 解题报告
- [leetcode] 384. Shuffle an Array
- 【leetcode】384. Shuffle an Array
- 384.[LeetCode]Shuffle an Array
- [LeetCode]384. Shuffle an Array
- [LeetCode] 384. Shuffle an Array
- LeetCode 384. Shuffle an Array
- LeetCode 384. Shuffle an Array
- LeetCode 384. Shuffle an Array
- [Leetcode]384. Shuffle an Array
- 【LeetCode】 384. Shuffle an Array
- [leetcode]384. Shuffle an Array
- LeetCode 384. Shuffle an Array
- [LeetCode]384. Shuffle an Array
- [LeetCode]384. Shuffle an Array
- leetcode 384. Shuffle an Array
- 内存分析工具MAT的使用
- kafka总结
- POJ2331 Water Pipe 解题报告
- tcp初级用法:局域网聊天室-1对1-带文件传输
- 学习MVC框架的步骤
- [leetcode] 384. Shuffle an Array 解题报告
- Java基础-集合框架简要概述
- 创建AOP代理步骤
- leakcanary原理分析与AppsFly内存泄漏
- 判断固定范围内的一组数中含有7或者是7的倍数的数
- 在64位linux下编译32位程序
- Spring中 @Autowired注解与@Resource注解的区别
- 在a标签中使用javascript
- An Old Problem