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