Java実装LeetCode 384動揺配列

384動揺配列

配列要素が繰り返しではありません混乱させる。

例:

//デジタルセット1、図2及び図3は、配列を初期化します。
INT [] = {1,2,3} NUMS;
ソリューションソリューションソリューション新しい新=(NUMS)。

//動揺配列[1,2,3]および結果を返します。任意の確率[1,2,3]は同じでなければならない戻さ配置されています。
solution.shuffle();

//初期状態配列[1,2,3]にリセットします。
solution.reset();

//は崩壊のランダムな配列[1,2,3]の結果を返します。
solution.shuffle();

class Solution {

     private int[] nums;
    private int[] originalNums;

    public Solution(int[] nums) {
        this.nums = nums;
        this.originalNums = Arrays.copyOf(nums, nums.length);
    }

    /**
     * Resets the array to its original configuration and return it.
     */
    public int[] reset() {
        return this.originalNums;
    }

    /**
     * Returns a random shuffling of the array.
     */
    public int[] shuffle() {
        Random random = new Random();
        for (int i = 0; i < nums.length / 2; i++) {
            // 每次只需拿第一个元素进行交换即可
            swap(nums, 0, random.nextInt(nums.length));
        }
        return nums;
    }

    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();
 */
リリース1496元の記事 ウォンの賞賛20000 + ビュー189万+

おすすめ

転載: blog.csdn.net/a1439775520/article/details/104807990