作者: 负雪明烛
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. du命令之计算文件大小

    在linux中,常用du命令来计算文件或目录的大小 名称: du - 计算每个文件的磁盘用量,目录则取总用量. 用法: du [选项]... [文件]... 常用选项 -a, --all 输出所有文件 ...

  2. 9. Delete Node in a Linked List

    Write a function to delete a node (except the tail) in a singly linked list, given only access to th ...

  3. LATEX公式语法

    see how any formula was written in any question or answer, including this one, right-click on the ex ...

  4. 避免UE4项目VS中误改源码.h文件导致编译时间长

    最近几天两次触发VS中误改UE4源码头文件,导致需要编译大量源码的情况:再好的习惯也有不可靠的时候,还是需要可靠方案解决这个问题:官方提供了预编译版本(即从Launcher中下载的版本),但是对于程序 ...

  5. Spark(四)【RDD编程算子】

    目录 测试准备 一.Value类型转换算子 map(func) mapPartitions(func) mapPartitions和map的区别 mapPartitionsWithIndex(func ...

  6. angular中路由跳转并传值四种方式

    一.路由传值 步骤1 路由传递参数 注意 一定是要传递 索引值 let key = index 这种情况是在浏览器中可以显示对应的参数 这种的是问号 localhost:8080/news?id=2& ...

  7. SqlSession与SqlSessionFactory到底是什么关系?

    1. SqlSession和SqlSessionFactory的接口定义 SqlSession: public interface SqlSession extends Closeable {     ...

  8. java代码定时备份mysql数据库及注意事项——基于 springboot

    源码地址: https://gitee.com/kevin9401/BackUpDataBase git 拉取: https://gitee.com/kevin9401/BackUpDataBase. ...

  9. SpringAOP浅析

    1.问题 问题:想要添加日志记录.性能监控.安全监测 2.最初解决方案 2.1.最初解决方案 缺点:太多重复代码,且紧耦合 2.2.抽象类进行共性设计,子类进行个性设计,此处不讲解,缺点一荣俱荣,一损 ...

  10. 【编程思想】【设计模式】【行为模式Behavioral】观察者模式Observer

    Python转载版 https://github.com/faif/python-patterns/blob/master/behavioral/observer.py #!/usr/bin/env ...