[LeetCode] Inplace random shuffling an array
来源:互联网 发布:手机地图导航软件 编辑:程序博客网 时间:2024/06/07 23:04
public void shuffle(int[] A) { if (A == null || A.length == 0) return; for (int i = 0; i < A.length-1; ++i) { int random = Math.random()*(A.length-i) + i; int temp = A[i]; A[i] = A[random]; A[random] = temp; }}
justification: Mostly from Here
For each element, it has same probability to go to each position
Step 1. The probability that ith element (including the first one) goes to first position is 1/n, because we randomly pick an element in first iteration.
Step 2. The probability that ith element goes to second position (position 1) can be proved to be 1/n by dividing it in two cases.
Case 1: for the 1st element (position 0)
Probability that the 1st element was switch with the second element in the previous step, thus it’s now at the second position
Case 2: i <= i < n (index of non-first):
The probability of ith element going to second position = (probability that ith element is not picked in previous iteration) x (probability that ith element is picked in this iteration)
So the probability = ((n-1)/n) x (1/(n-1)) = 1/n
- [LeetCode] Inplace random shuffling an array
- array shuffling
- 【Leetcode】Shuffle an Array
- LeetCode:384 Shuffle an Array
- leetcode之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
- 算法-逆序对
- 为什么匿名内部类和局部内部类只能访问final变量
- Visual C++ 6.0 操作excel2003进行图表绘制
- win7下IIS的安装步骤
- javascript控制input不可写
- [LeetCode] Inplace random shuffling an array
- The recycle times and the feature of the top grade dynea brown film faced plywood
- 线程最最基本的操作1,(用到了waitforsinglobject)
- Memcached保存sesion数据的方法以及安全性问题
- Socket服务器端
- CABasicAnimation介绍
- 处理使用node-gpy时遇到的Can't find "msbuild.exe"错误
- Android学习笔记之----浅析Android进程与线程
- 网络框架Volley