LeetCode-探索-初级算法-设计问题-1. Shuffle an Array(个人做题记录,不是习题讲解)
LeetCode探索-初级算法:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/
- Shuffle an Array
-
语言:java
-
思路:看了网上说打乱的方法就是从尾部到头部遍历的时候生成随机数,然后进行位置调换。还原就没什么好说的了。
https://blog.csdn.net/m0_38082783/article/details/79579116
-
代码(218ms,84.32%,还行吧):
class Solution { public int[] raw; public int[] backpack; public int len; public Solution(int[] nums) { raw = nums; len = nums.length; backpack = new int[len]; System.arraycopy(nums,0,backpack,0,len); } /** Resets the array to its original configuration and return it. */ public int[] reset() { return raw; } /** Returns a random shuffling of the array. */ public int[] shuffle() { for(int i = len - 1; i >= 0; --i){ int j = (int)(Math.random() * len); int tmp = backpack[i]; backpack[i] = backpack[j]; backpack[j] = tmp; } return backpack; } } /** * 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(); */
-
参考代码(120ms):整体思路时一样的,都是从尾到头,生成随机数来表示替换的下标,然后进行"随机“替换
class Solution { private int[] original; private int[] arr; private Random r; public Solution(int[] nums) { original = nums; arr = Arrays.copyOf(nums, nums.length); r = new Random(); } /** Resets the array to its original configuration and return it. */ public int[] reset() { System.arraycopy(original, 0, arr, 0, original.length); return arr; } /** Returns a random shuffling of the array. */ public int[] shuffle() { for(int n = arr.length; n > 1; n--) { swap(arr, n - 1, r.nextInt(n)); } return arr; } private void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } } /** * 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(); */