【LeetCode】 384. 打乱数组

题目

题目传送门:传送门(点击此处)
在这里插入图片描述

题解

  1. 直接看到题目,也应该想到要用随机数了,第一点要考虑的就是随机数怎么用
  2. 考虑到有一个reset(),还有一个shuffle(),很简单的办法,克隆一份保存起来,因为数组是传引用的,所以不可以直接赋值
  3. 我在考虑了随机数之后,思路其实还蛮简单的,根据索引,在数组长度范围内,随机取一个下标的值和当前索引的值交换

代码

class Solution {

    int[] nums;
    int[] backNums; // 数组备份

    public Solution(int[] nums) {
        this.nums = nums;
        backNums = nums.clone();
    }

    /**
     * Resets the array to its original configuration and return it.
     */
    public int[] reset() {
        nums = backNums.clone();
        return nums;
    }

    /**
     * Returns a random shuffling of the array.
     */
    public int[] shuffle() {
        int n = nums.length;
        Random random = new Random();
        for (int i = 0; i < n; i++) {
            int p = random.nextInt(n);
            int temp = nums[i];
            nums[i] = nums[p];
            nums[p] = temp;
        }
        return nums;
    }
}

/**
 * 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();
 */
发布了151 篇原创文章 · 获赞 148 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq1515312832/article/details/104439809
今日推荐