博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leetcode]384. Shuffle an Array洗牌
阅读量:4572 次
发布时间:2019-06-08

本文共 1819 字,大约阅读时间需要 6 分钟。

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

 

题意:

洗牌

 

Solution1:

 

code

1 class Solution { 2     int[] origin; 3     int[] nums; 4     Random random; 5  6     public Solution(int[] nums) { 7         origin = copy(nums); 8         this.nums = copy(nums); 9         random = new Random();10     }11 12     /** Resets the array to its original configuration and return it. */13     public int[] reset() {14         nums = copy(origin);15         random = new Random();16         return nums;17 18     }19 20     /** Returns a random shuffling of the array. */21     public int[] shuffle() {22         final int n = nums.length;23         int[] result = new int[n];24 25         for(int i = n; i>=1; i--){26             int randomIdx = random.nextInt(i);27             result[n - i] = nums[randomIdx];28             int temp = nums[randomIdx];29             nums[randomIdx] = nums[i - 1];30             nums[i - 1] = temp;31         }32         return result;33     }34 35     private int[] copy(int[] array){36         int[] result = new int[array.length];37         for(int i = 0; i < array.length; i++){38             result[i] = array[i];39         }40         return result;41     }42 }43 44 /**45  * Your Solution object will be instantiated and called as such:46  * Solution obj = new Solution(nums);47  * int[] param_1 = obj.reset();48  * int[] param_2 = obj.shuffle();49  */

 

转载于:https://www.cnblogs.com/liuliu5151/p/10823254.html

你可能感兴趣的文章
React Children
查看>>
大数据等最核心的关键技术:32个算法
查看>>
Maven多模块项目搭建
查看>>
Scala
查看>>
Android 中LinearLayout控件属性
查看>>
面向对象之多态性
查看>>
树状数组
查看>>
【2019.8.14 慈溪模拟赛 T1】我不是!我没有!别瞎说啊!(notme)(BFS+DP)
查看>>
多任务--进程 及 进程间通信
查看>>
多线程/多进程+QProgressBar实现进度条
查看>>
多任务(进程)案例----- 拷贝文件夹
查看>>
Kotlin的快速入门
查看>>
底层原理
查看>>
21. Merge Two Sorted Lists
查看>>
创建数组
查看>>
dict使用
查看>>
ASP.NET MVC的帮助类HtmlHelper和UrlHelper
查看>>
02_ListActive中响应事件 并LogCat输出
查看>>
doubleclick adx note
查看>>
Celery框架
查看>>