[Leetcode]384. Shuffle an Array
来源:互联网 发布:网络出版服务许可单位 编辑:程序博客网 时间:2024/06/06 17:12
题目[leetcode链接]
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();
思路:
随机洗牌问题
从头开始遍历,每次在[0,len)之间产生一个随机数,交换遍历到的位置与随机数位置上的数。
具体代码实现:
public class Solution { int[] nums; int[] result; public Solution(int[] nums) { int len = nums.length; this.nums = new int[len]; result = new int[len]; for (int i = 0; i < len; i++) { this.nums[i] = nums[i]; result[i] = nums[i]; } } /* 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() { int nums_len = nums.length; Random random = new Random(); for (int i = 0; i < nums_len; i++) { int r = random.nextInt(nums_len); int temp = result[i]; result[i] = result[r]; result[r] = temp; } return result; }}
需要注意的问题:
返回值result的创建不能在shuffle()函数中创建,这样每次shuffle都会新创建空间,浪费很多空间,应该如代码中写的 在类中创建一个成员变量,每次用都用这个就可以。
0 0
- [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
- [LeetCode]384. Shuffle an Array
- [LeetCode]384. Shuffle an Array
- leetcode 384. Shuffle an Array
- 384. Shuffle an Array [Leetcode]
- LeetCode:384. Shuffle an Array
- 【Leetcode】Shuffle an Array
- [OpenGL] obj文件解析
- Vysor PRO 破解方法
- 使用canal进行mysql数据同步到Redis
- WebAdmin
- iOS8 获取视频缩略图带有时间,怎么获取
- [Leetcode]384. Shuffle an Array
- 前端单元测试工具-karma
- 线性代数复习分析(矩阵代数运算)
- checkbox 复选框只选择一个
- Android、Java错误集
- SPPNet论文笔记和caffe实现说明
- OBJ文件格式详解
- Android小知识
- 如何从一个svn地址切换到另一个地址