LeetCode——第384題:打亂數組

參考

題目:

打亂一個沒有重複元素的數組。

示例:

// 以數字集合 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();

代碼:

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Random;

/**
 * @作者:dhc
 * @創建時間:9:06 2018/8/4
 * @描述:384,打亂數組
 */
public class ThreeHundredAndEightFour {
    private static int[] arr1;
    private static int[] arr2;
    public ThreeHundredAndEightFour(int[] nums){
        arr1 = nums;
    }
    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        return  arr1;
    }

    /** Returns a random shuffling of the array. */
    //洗牌算法
    public  static int[] shuffle() {
        arr2 = new int[arr1.length];
        System.arraycopy(arr1,0,arr2,0,arr1.length);
        /*for (int i = 0; i < arr1.length; i++) {
            arr2[i] = arr1[i];
        }*/
        Random ran = new Random();
        for(int i = 0; i < arr2.length;i++){
            //這裏不能用int random = (int)(Math.random()*(arr2.length));,這樣最後的
            // 每種結果概率是不一樣的
            //int random = (int)(Math.random()*(i+1));
            int random = ran.nextInt(i);
            int tem = arr2[random];
            arr2[random] = arr2[i];
            arr2[i] = tem;
        }
        return arr2;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章