[LeetCode] 384. Shuffle an Array

题:https://leetcode.com/problems/shuffle-an-array/description/

题目

Shuffle a set of numbers without duplicates.

Example:

// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);

// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
solution.shuffle();

// Resets the array back to its original configuration [1,2,3].
solution.reset();

// Returns the random shuffling of array [1,2,3].
solution.shuffle();

思路

题目大意

实现一个洗牌类的相关方法。

  1. 构造方法 将待洗牌的 int []nums传入。
  2. 方法reset(),返回 最初的 nums数组。
  3. 方法shuffle(),返回 对nums的洗牌结果。

什么是洗牌 shuffle() ,参考 : https://blog.csdn.net/happiness2018/article/details/80371458

解题思路

类成员变量 生成一份 nums的备份供 方法reset() 使用。
shuffle() 实现是 从nums中选出第1个位置,再从nums中 n个元素(包括自己) 交换,确定第1个位置。然后选出第 2个位置,再从剩下的n-1个元素(包括自己)交换。直到只剩最后一个元素。

参考:https://www.jianshu.com/p/44100741cef5

code

class Solution {
    int[] backup_nums;
    int[] nums;
    Random rd = new Random();
    public Solution(int[] nums) {
        this.backup_nums = nums;

        this.nums = nums.clone();
    }

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

    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        int n = this.nums.length;
        while(n>1){
            n--;
            int k = rd.nextInt(n+1);
            int value = this.nums[k];
            this.nums[k] = this.nums[n];
            this.nums[n] = value;
        }
        return this.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();
 */

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/82936286