leetcode 384. Shuffle an Array | 384. 打乱数组(Fisher-Yates洗牌算法)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 384. Shuffle an Array | 384. 打乱数组(Fisher-Yates洗牌算法)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
https://leetcode.com/problems/shuffle-an-array/
題解
本代碼參考了 JDK 源碼 Collections.shuffle() 的實現,也可以看 官方題解
class Solution {int[] nums;public Solution(int[] nums) {this.nums = nums;}/*** 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[] arr = new int[nums.length];System.arraycopy(nums, 0, arr, 0, nums.length);// this is how Collections.shuffle() implementsRandom r = new Random();for (int i = arr.length; i > 1; i--)swap(arr, i - 1, r.nextInt(i));return arr;}public void swap(int[] arr, int i, int j) {int t = arr[i];arr[i] = arr[j];arr[j] = t;} }/*** Your Solution object will be instantiated and called as such:* Solution obj = new Solution(nums);* int[] param_1 = obj.reset();* int[] param_2 = obj.shuffle();*/總結
以上是生活随笔為你收集整理的leetcode 384. Shuffle an Array | 384. 打乱数组(Fisher-Yates洗牌算法)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 372. Super
- 下一篇: leetcode 131. Palind