编程语言
首页 > 编程语言> > LeetCode-每日一题 384. 打乱数组 [Java实现]

LeetCode-每日一题 384. 打乱数组 [Java实现]

作者:互联网

给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。

实现 Solution class:

示例

输入
["Solution", "shuffle", "reset", "shuffle"]
[[[1, 2, 3]], [], [], []]
输出
[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]

解释
Solution solution = new Solution([1, 2, 3]);
solution.shuffle();    // 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。例如,返回 [3, 1, 2]
solution.reset();      // 重设数组到它的初始状态 [1, 2, 3] 。返回 [1, 2, 3]
solution.shuffle();    // 随机返回数组 [1, 2, 3] 打乱后的结果。例如,返回 [1, 3, 2]


方法一:洗牌

        对于数组中的第 i 位,我们在打乱时将其与第 [i, n) 位的数字随机交换值即可做到每个元素都可等概率的出现在每个位置上。

class Solution {
        private final int[] nums;
        private final Random random = new Random();
        private final int n;

        public Solution(int[] nums) {
            this.nums = nums;
            this.n = nums.length;
        }

        public int[] reset() {
            return nums;
        }

        public int[] shuffle() {
            int[] result = nums.clone();
            for (int i = 0; i < n; ++ i)
                swap(result, i, i+random.nextInt(n-i));
            return result;
        }

        private static void swap(int[] ints, int i, int j) {
            int temp = ints[j];
            ints[j] = ints[i];
            ints[i] = temp;
        }

    }

标签:Java,ints,nums,int,Solution,384,数组,shuffle,LeetCode
来源: https://blog.csdn.net/qq_51026595/article/details/121467665