LeetCode: 384. 打乱数组(Java)

题目:

打乱一个没有重复元素的数组。

示例:

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

解答:

这个题要用两个数组,一个存储原来的数据,一个存储工作的数据。

首次:不要用=(等号是把两个引用指向统一位置),要记得复制数组。

方法是:复制后,以i逆序遍历工作数组,可以在[0 - i]中随机选一个数,这个数是工作数组中被选中数的索引,然后将被选中的数与第i个数交换位置。

import java.util.Random;

class Solution {
    private int[] originalNums;
    private int[] currentNums;

    public Solution(int[] nums) {
        originalNums = nums;
    }
    
    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        return originalNums;
    }
    
    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        currentNums = Arrays.copyOf(originalNums, originalNums.length);
        Random randNum = new Random();
        for (int i = currentNums.length - 1; i >= 0; i--) {
            int selectedElem = randNum.nextInt(i + 1);
            
            int temp = currentNums[selectedElem];
            currentNums[selectedElem] = currentNums[i];
            currentNums[i] = temp;
        }
        return currentNums;
    }
}

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

猜你喜欢

转载自blog.csdn.net/souloh/article/details/81097397
今日推荐