【Leetcode】Shuffle an Array
题目链接: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();
Subscribe to see which companies asked this question
思路:
使用 http://blog.csdn.net/yeqiuzs/article/details/52141124 中实现的数据结构,每次shuffle时 先获取初始集合一个随机数并删除,直至集合为空,一次shuffle完成,完成后需要恢复该存储集合的数据结构。 时间复杂度shuffle方法 O(n),reset方法O(n),构造方法O(n)。
这题我做复杂了。。不要这么做。。
最简单的方法是对数组做n次随机交换。。
算法:
public class Solution {RandomizedSet rm;int nums[];public Solution(int[] nums) {rm = new RandomizedSet();this.nums = nums;for (int i=0;i<nums.length;i++) {rm.insert(nums[i]);}}/** Resets the array to its original configuration and return it. */public int[] reset() {rm = new RandomizedSet();for (int i=0;i<nums.length;i++) {rm.insert(nums[i]);}return nums;}/** Returns a random shuffling of the array. */public int[] shuffle() {RandomizedSet tmp = new RandomizedSet();int[] res = new int[rm.vals.size()];for (int i = 0; i < res.length; i++) {res[i] = rm.getRandom();rm.remove(res[i]);tmp.insert(res[i]);}rm = tmp;return res;}class RandomizedSet {/** Initialize your data structure here. */public RandomizedSet() {}List<Integer> vals = new ArrayList<Integer>();Map<Integer, Integer> val2idx = new HashMap<Integer, Integer>();/*** Inserts a value to the set. Returns true if the set did not already* contain the specified element.*/public boolean insert(int val) {if (val2idx.containsKey(val)) {return false;} else {val2idx.put(val, val2idx.size());vals.add(val);return true;}}/*** Removes a value from the set. Returns true if the set contained the* specified element.*/public boolean remove(int val) {if (!val2idx.containsKey(val)) {return false;} else {int idx = val2idx.remove(val);if (idx < vals.size() - 1) {// 若删除的不是链表最后的元素// 交换末尾元素和被删除元素vals.set(idx, vals.get(vals.size() - 1));val2idx.put(vals.get(vals.size() - 1), idx);}vals.remove(vals.size() - 1);return true;}}/** Get a random element from the set. */Random r = new Random();public int getRandom() {return vals.get(r.nextInt(vals.size()));}}}
【Leetcode】Shuffle an Array相关推荐
- 【leetcode】Merge Sorted Array
题目描述 Given two sorted integer arrays A and B, merge B into A as one sorted array. Note: You may assu ...
- 【leetcode】486. Predict the Winner
题目如下: Given an array of scores that are non-negative integers. Player 1 picks one of the numbers fro ...
- 【leetcode】109. Convert Sorted List to Binary Search Tree
题目如下: Given a singly linked list where elements are sorted in ascending order, convert it to a heigh ...
- 【leetcode】41. First Missing Positive
题目如下: 解题思路:这题看起来和[leetcode]448. Find All Numbers Disappeared in an Array很相似,但是有几点不同:一是本题的输入存在负数,二是没有 ...
- 【LeetCode】【HOT】49. 字母异位词分组(递归)
[LeetCode][HOT]49. 字母异位词分组 文章目录 [LeetCode][HOT]49. 字母异位词分组 package hot;import java.util.ArrayList; i ...
- 【LeetCode】309. Best Time to Buy and Sell Stock with Cooldown 最佳买卖股票时机含冷冻期(Medium)(JAVA)
[LeetCode]309. Best Time to Buy and Sell Stock with Cooldown 最佳买卖股票时机含冷冻期(Medium)(JAVA) 题目地址: https: ...
- 【LeetCode】163.Missing Ranges(Medium)(带锁题)解题报告
[LeetCode]163.Missing Ranges(Medium)(带锁题)解题报告 题目地址:https://leetcode.com/problems/missing-ranges/(带锁题 ...
- 【LeetCode】2022 7月 每日一题
[LeetCode]2022 7月 每日一题 前言 七月太忙了,又是项目又是练车又是各种比赛.大概有10天的每日一题没有当天写完(虽然后面补上了). 将每日一题的所有思路记录在这里分享一下. 7.1 ...
- 【LeetCode 】试题总结:广度优先搜索(BFS)
[LeetCode ]试题总结:广度优先搜索(BFS) 一.数据结构:二叉树中的 BFS (一).二叉树的堂兄弟节点 试题链接 解题思路 代码 (二).二叉树的层序遍历 II (三).二叉树的锯齿形层 ...
最新文章
- Linux下GBK文件编码批量转换UTF-8命令
- Codeforces Round #368 (Div. 2) problem: (C) Pythagorean Triples
- DSP2812程序执行过程
- SpringMVC的请求-获得请求参数-静态资源访问的开启
- How does framework require TechnicalInfo.js
- c语言如何随机获取1kb,基于VS2010+C语言实现播放器的顺序播放、随机播放
- mysql日期格式化季度_mysql 按年度、季度、月度、周、日SQL统计查询
- os模块,序列化模块,json模块,pickle模块
- C++ 编译运行报错 error: stray ‘\200’ in program 解决方案
- 使用spring的事务的三种方法
- pgAdmin4数据库备份还原
- 人工智能系列 之机器学习DBSCAN聚类算法
- python生成倒计时图片_用Python自动化生成新年倒计时图片
- 工业云计算技术在工业自动化系统中的作用
- vue校验输入框不能有中文
- 达梦数据库备份方法总结学习
- springcloud官方文档,中英文双版
- WinRAR压缩命令
- 打印魔方阵(C语言)
- python代码画樱花带图片_python编程——pygame画樱花树