Leetcode題解之設計問題(1)shuffle an arrays
阿新 • • 發佈:2018-12-02
題目:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/24/design/58/
題目描述:
打亂一個沒有重複元素的陣列。
示例:
// 以數字集合 1, 2 和 3 初始化陣列。 int[] nums = {1,2,3}; Solution solution = new Solution(nums); // 打亂陣列 [1,2,3] 並返回結果。任何 [1,2,3]的排列返回的概率應該相同。 solution.shuffle(); // 重設陣列到它的初始狀態[1,2,3]。 solution.reset(); // 隨機返回陣列[1,2,3]打亂後的結果。 solution.shuffle();
思路:需要兩個陣列。一個是記錄沒變化的陣列,一個用於操作。這裡沒用for迴圈賦值獲得可運算元組。用的是Arrays.copyOf方法。如果直接用 = 號 ,不是複製陣列!只是共同引用一個數組的地址!操作部分。用Random類 的ran.nextInt()方法獲得偽隨機數。然後用一個數記錄隨機數。隨機數的位置和i互換。其中temp 用於記錄交換值。
對了,剛開始在構造方法 重新 int[] orgin = nums;是錯的!這樣全域性變數orgin 並沒有獲得nums地址。
程式碼:
class Solution { private int[] orgin; private int[] cur; public Solution(int[] nums) { orgin = nums; } /** Resets the array to its original configuration and return it. */ public int[] reset() { return orgin; } /** Returns a random shuffling of the array. */ public int[] shuffle() { cur = Arrays.copyOf(orgin,orgin.length); Random ran = new Random(); for(int i=orgin.length-1;i>=0;i--){ int x = ran.nextInt(i+1); int temp = cur[x] ; cur[x]=cur[i]; cur[i]= temp; } return cur; } }