作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/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();

题目大意

定义两个函数,shuffle函数能把数组随机打乱,reset函数能返回初始数组。

解题方法

库函数

直接调用python的random.shuffle就行了。C++也有std::random_shuffle()函数。

注意都是原地打乱。

Python代码如下:

import random
class Solution(object): def __init__(self, nums):
"""
:type nums: List[int]
"""
self.nums = nums def reset(self):
"""
Resets the array to its original configuration and return it.
:rtype: List[int]
"""
return self.nums def shuffle(self):
"""
Returns a random shuffling of the array.
:rtype: List[int]
"""
nums_s = self.nums[:]
random.shuffle(nums_s)
return nums_s # Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()

C++代码如下:

class Solution {
private:
vector<int> nums_;
vector<int> toshuffle_;
public:
Solution(vector<int> nums) {
nums_ = nums;
toshuffle_ = nums;
} /** Resets the array to its original configuration and return it. */
vector<int> reset() {
toshuffle_ = nums_;
return nums_;
} /** Returns a random shuffling of the array. */
vector<int> shuffle() {
random_shuffle(toshuffle_.begin(), toshuffle_.end());
return toshuffle_;
}
}; /**
* 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();
*/

Fisher–Yates 洗牌

新学习了Fisher–Yates shuffle 洗牌算法。

Fisher–Yates shuffle 的原始版本,最初描述在 1938 年的 Ronald Fisher 和 Frank Yates 写的书中,书名为《Statistical tables for biological, agricultural and medical research》。他们使用纸和笔去描述了这个算法,并使用了一个随机数表来提供随机数。它给出了 1 到 N 的数字的的随机排列,具体步骤如下:

  1. 写下从 1 到 N 的数字
  2. 取一个从 1 到剩下的数字(包括这个数字)的随机数 k
  3. 从低位开始,得到第 k个数字(这个数字还没有被取出),把它写在独立的一个列表的最后一位
  4. 重复第 2步,直到所有的数字都被取出
  5. 第 3 步写出的这个序列,现在就是原始数字的随机排列

已经证明如果第 2 步取出的数字是真随机的,那么最后得到的排序一定也是。

洗牌的过程可以看看这个文章,看一遍一定就懂!https://gaohaoyang.github.io/2016/10/16/shuffle-algorithm/

这个算法的一句话总结:依次遍历列表中的每一位,并将这一位与其后面的随机一位交换顺序。

import random
class Solution(object): def __init__(self, nums):
"""
:type nums: List[int]
"""
self.nums = nums def reset(self):
"""
Resets the array to its original configuration and return it.
:rtype: List[int]
"""
return self.nums def shuffle(self):
"""
Returns a random shuffling of the array.
:rtype: List[int]
"""
nums_s = self.nums[:]
_len = len(self.nums)
for i in xrange(_len):
rand = random.randrange(i, _len)
nums_s[i], nums_s[rand] = nums_s[rand], nums_s[i]
return nums_s # Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()

水塘抽样

另外一个抽样算法叫做水塘抽样,其本来的目的是在大数据流中的随机抽样问题,即:当内存无法加载全部数据时,如何从包含未知大小的数据流中随机选取k个数据,并且要保证每个数据被抽取到的概率相等。

  1. 当K = 1时,数据流中第i个数被保留的概率为 1/i。只要采取这种策略,只需要遍历一遍数据流就可以得到采样值,并且保证所有数被选取的概率均为 1/N 。
  2. 当K > 1时,对于前k个数,我们全部保留,对于第i(i>k)个数,我们以K/i的概率保留第i个数,并以 1/K的概率与前面已选择的k个数中的任意一个替换。

证明过程:https://zhuanlan.zhihu.com/p/29178293

至于这个题的随机打乱,其实就是在长度K的数据中,随机选K个数字的问题,方法变成了和Fisher–Yates 洗牌完全一样了,一句话总结就是:依次遍历列表中的每一位,并将这一位与其后面的随机一位交换顺序。

C++代码如下:

class Solution {
private:
vector<int> nums_;
public:
Solution(vector<int> 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() {
vector<int> res = nums_;
for (int i = 0; i < res.size(); ++i) {
int t = i + rand() % (res.size() - i);
swap(res[i], res[t]);
}
return res;
}
}; /**
* 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();
*/

日期

2018 年 2 月 27 日
2019 年 2 月 22 日 —— 这周结束了

【LeetCode】384. Shuffle an Array 解题报告(Python & C++)的更多相关文章

  1. leetcode 384. Shuffle an Array

    384. Shuffle an Array c++ random函数:https://www.jb51.net/article/124108.htm rand()不需要参数,它会返回一个从0到最大随机 ...

  2. [LeetCode] 384. Shuffle an Array 数组洗牌

    Shuffle a set of numbers without duplicates. Example: // Init an array with set 1, 2, and 3. int[] n ...

  3. Java [Leetcode 384]Shuffle an Array

    题目描述: Shuffle a set of numbers without duplicates. Example: // Init an array with set 1, 2, and 3. i ...

  4. 【LeetCode】26. Remove Duplicates from Sorted Array 解题报告(Python&C++&Java)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 双指针 日期 [LeetCode] https:// ...

  5. 【LeetCode】525. Contiguous Array 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 累积和 日期 题目地址:https://leetco ...

  6. 【LeetCode】896. Monotonic Array 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  7. 【LeetCode】932. Beautiful Array 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 构造法 递归 相似题目 参考资料 日期 题目地址:h ...

  8. 【LeetCode】189. Rotate Array 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 切片 递归 日期 题目地址:https://leet ...

  9. 【LeetCode】62. Unique Paths 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/unique-pa ...

随机推荐

  1. react native安装遇到的问题

    最近学习react native 是在为全栈工程师而努力,看网上把react native说的各种好,忍不住学习了一把.总体感觉还可以,特别是可以开发android和ios这点非常厉害,刚开始入门需要 ...

  2. Beautiful Soup解析库的安装和使用

    Beautiful Soup是Python的一个HTML或XML的解析库,我们可以用它来方便地从网页中提取数据.它拥有强大的API和多样的解析方式.官方文档:https://www.crummy.co ...

  3. Vue相关,Vue生命周期及对应的行为

    先来一张经典图 生命钩子函数 使用vue的朋友们知道,生命周期函数长这样- mounted: function() { } // 或者 mounted() { } 注意点,Vue的所有生命周期函数都是 ...

  4. C逗号表达式

    c语言提供一种特殊的运算符,逗号运算符,优先级别最低,它将两个及其以上的式子联接起来,从左往右逐个计算表达式,整个表达式的值为最后一个表达式的值.如:(3+5,6+8)称为逗号表达式,其求解过程先表达 ...

  5. jdk1.6,1.7,1.8解压版无需安装(64位)

    1.java SE 1.6各个版本 jdk http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads ...

  6. Oracle trunc和round的区别

    1.关于trunc 和round函数比较 整体概括: round函数 四舍五入trunc函数 直接截取 对于时间: Round函数对日期进行"四舍五入",Trunc函数对日期进行截 ...

  7. OpenStack之九: 创建一个实例

    官网地址 https://docs.openstack.org/install-guide/launch-instance-networks-provider.html #:导入变量 [root@co ...

  8. Gitlab安装操作说明书

    一.Gitlab安装操作步骤 登录官方网站https://about.gitlab.com/downloads/根据你所需要的系统版本,作者使用的是centos6, 检查您的服务器是否符合硬件要求.g ...

  9. Linux 双网卡绑定及Bridge

    Linux 双网卡绑定及Bridge 阅读(5,202) 一:linux操作系统下双网卡绑定有七种模式.现在一般的企业都会使用双网卡接入,这样既能添加网络带宽,同时又能做相应的冗余,可以说是好处多多. ...

  10. 关于requests.exceptions.ConnectionError: HTTPSConnectionPool的问题

    错误如下: raise ConnectionError(e, request=request)requests.exceptions.ConnectionError: HTTPSConnectionP ...