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();

给一个没有重复数字的数组,实现重置和洗牌的功能。

解法:遍历数组每个位置,每次都随机生成一个坐标位置,然后交换当前位置和随机位置的数字,这样如果数组有n个数字,那么也随机交换了n组位置,从而达到了洗牌的目的。

Java:

import java.util.Random;

public class Solution {
private int[] nums;
private Random random; public Solution(int[] nums) {
this.nums = nums;
random = new Random();
} /** Resets the array to its original configuration and return it. */
public int[] reset() {
return nums;
} /** Returns a random shuffling of the array. */
public int[] shuffle() {
if(nums == null) return null;
int[] a = nums.clone();
for(int j = 1; j < a.length; j++) {
int i = random.nextInt(j + 1);
swap(a, i, j);
}
return a;
} private void swap(int[] a, int i, int j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}  

Python:

import random

class Solution(object):

    def __init__(self, nums):
"""
:type nums: List[int]
:type size: 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 = list(self.__nums)
for i in xrange(len(nums)):
j = random.randint(i, len(nums)-1)
nums[i], nums[j] = nums[j], nums[i]
return nums # Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()  

C++:

class Solution {
public:
Solution(vector<int> nums): v(nums) {} /** Resets the array to its original configuration and return it. */
vector<int> reset() {
return v;
} /** Returns a random shuffling of the array. */
vector<int> shuffle() {
vector<int> res = v;
for (int i = 0; i < res.size(); ++i) {
int t = i + rand() % (res.size() - i);
swap(res[i], res[t]);
}
return res;
} private:
vector<int> v;
};

  

All LeetCode Questions List 题目汇总

[LeetCode] 384. Shuffle an Array 数组洗牌的更多相关文章

  1. 384. Shuffle an Array数组洗牌

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

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

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

  3. leetcode 384. Shuffle an Array

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

  4. Java [Leetcode 384]Shuffle an Array

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

  5. 数组洗牌算法-shuffle

    数组洗牌,最近直接的想法是从数组随机取出一个元素,放到另一个数组中,但是这样取出的元素会有重复,必须采取一定的方法保证: 1. 元素不能重复2. 元素被抽取的概率相等,即随机性 数组洗牌经典算法有两种 ...

  6. POJ 3087 Shuffle'm Up(洗牌)

    POJ 3087 Shuffle'm Up(洗牌) Time Limit: 1000MS    Memory Limit: 65536K Description - 题目描述 A common pas ...

  7. 【LeetCode】384. Shuffle an Array 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 库函数 Fisher–Yates 洗牌 水塘抽样 日 ...

  8. 384 Shuffle an Array 打乱数组

    打乱一个没有重复元素的数组.示例:// 以数字集合 1, 2 和 3 初始化数组.int[] nums = {1,2,3};Solution solution = new Solution(nums) ...

  9. 384. Shuffle an Array

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

随机推荐

  1. Product Oriented Recurrence(Codeforces Round #566 (Div. 2)E+矩阵快速幂+欧拉降幂)

    传送门 题目 \[ \begin{aligned} &f_n=c^{2*n-6}f_{n-1}f_{n-2}f_{n-3}&\\ \end{aligned} \] 思路 我们通过迭代发 ...

  2. 实用Golang库

    框架: 1. Golang轻量级并发服务器框架: zinx / https://www.jianshu.com/p/23d07c0a28e52. 国内谢大牛模仿django制作的重框架: beego3 ...

  3. Top 20 IoT Platforms in 2018

    https://internetofthingswiki.com/top-20-iot-platforms/634/ After learning what is the internet of th ...

  4. TreeMap 的简单解释

    TreeMap的构造函数   可以传入 自定义的比较器.Map.SortedMap.   put方法: public V put(K key, V value) { Entry<K,V> ...

  5. Django 中使用redis

    Django使用redis   方式一,使用Django-redis模块 #安装: pip3 install django-redis CACHES = { "default": ...

  6. 洛谷 P2512 [HAOI2008]糖果传递 题解

    每日一题 day47 打卡 Analysis 首先,最终每个小朋友的糖果数量可以计算出来,等于糖果总数除以n,用ave表示. 假设标号为i的小朋友开始有Ai颗糖果,Xi表示第i个小朋友给了第i-1个小 ...

  7. Oracle 查看index是否失效

    一.普通索引是否失效 select * from dba_indexes s where s.owner  in ('ISMP','BOSS','PAY','ACCOUNT','SETTLE','TE ...

  8. learning java FileWriter

    import java.io.FileWriter; import java.io.IOException; public class FileWriterTest { public static v ...

  9. WinDbg常用命令系列---清屏

    .cls (Clear Screen) .cls命令清除调试器命令窗口显示. .cls 环境: 模式 用户模式下,内核模式 目标 实时. 崩溃转储 平台 全部 清屏前 清屏后

  10. Servlet使用反射机制

    传统servlet存在的问题 每一个不同的请求都要写Servlet,导致整个项目servlet过多,不易维护 解决方案 同一个模块只写一个Servlet,然后每一个请求传一个参数,后台根据参数取调用不 ...