384. Shuffle an Array(java,數組全排列,然后隨機取)


題目:

Shuffle a set of numbers without duplicates.

分析:

對一組不包含重復元素的數組進行隨機重排,reset方法返回最原始的數組,shuffle方法隨機返回數組的一個排列,

並且使得獲得數組每一個排列的概率都是相同的。為此,可以在初始化時,求出數組的所有排列。在使用shuffle方法時,隨機返回全排列中的一個。

代碼:

public class Solution {
    
    //存儲數組的所有排列
    List<int[]> list = new ArrayList<int[]>();
    public Solution(int[] nums) {
        //首先求所有排列
        permutations(nums,list,0);
    }
    
    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        return list.get(0);
    }
    
    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        int index = (int)(Math.random() * list.size());
        return list.get(index);
    }
    //求數組的所有排列
    public void permutations(int[] array,List<int[]> list,int start){
        if(array == null){
            return;
        }
        if(start == array.length){
            int[] temp = new int[array.length];
            System.arraycopy(array,0,temp,0,array.length);
            list.add(temp);
        }
        for(int i = start; i < array.length; ++i){
            swap(array,i,start);
            permutations(array,list,start+1);
            swap(array,i,start);
        }
    }
    //交換元素
    public void swap(int[] array,int i,int j){
        int temp = array[i];
        array[i] = array[j];
        array[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();
 */

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM