Leetcode:384.打乱数组

Leetcode: 384.打乱数组

题目描述

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

示例:

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

思路

思路1:复制数组+移除

复制一个新数组,然后随机置入数组,将置入数组的数移除

思路2:Fisher–Yates shuffle

遍历数组,随机化得到一个从当前位置到最后位置的数进行交换,该方法产生n!种可能,但是如果采用随机产生两个随机数则是错的,其产生的可能性为$n^n$,简单证明为n!可能不能被$n^n$整除

代码

代码1: 复制数组+移除

class Solution {
    private int[] nums;
    private int[] origins;
    
    private Random rand = new Random();
    
    public Solution(int[] nums) {
        this.nums = nums;
        origins = this.nums.clone();
    }
    
    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        this.nums = this.origins;
        this.origins = this.origins.clone();
        return this.nums;
    }
    
    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        List copyList = new ArrayList<>();
        for(int num: this.nums){
            copyList.add(num);
        }
        for(int i = 0; i < this.nums.length; i++){
            int removeIndex = rand.nextInt(copyList.size());
            this.nums[i] = copyList.get(removeIndex);
            copyList.remove(removeIndex);
        }
        return this.nums;
    }
}

代码2

class Solution {
    private int[] nums;
    private int[] origins;
    
    private Random rand = new Random();
    
    public Solution(int[] nums) {
        this.nums = nums;
        origins = this.nums.clone();
    }
    
    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        this.nums = this.origins;
        this.origins = this.origins.clone();
        return this.nums;
    }
    
    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        for(int i = 0; i < this.nums.length; i++){
            int swapIndex = rand.nextInt(this.nums.length - i) + i;
            int temp = this.nums[i];
            this.nums[i] = this.nums[swapIndex];
            this.nums[swapIndex] = temp;
        }
        return this.nums;
    }
}

复杂度分析

思路1时间复杂度

$O(n^2)$

思路1空间复杂度

$O(n)$

思路2时间复杂度

$O(n)$没有了移除操作

思路1空间复杂度

$O(n)$


文章作者: 小风雷
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 小风雷 !
评论
 上一篇
Leetcode:350. 两个数组的交集 II Leetcode:350. 两个数组的交集 II
350. 两个数组的交集 II题目描述给定两个数组,编写一个函数来计算它们的交集。 示例 1:输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2,2] 示例 2:输入: nums1 = [4,9,5]
2020-03-27
下一篇 
Leetcode:283. 移动零 Leetcode:283. 移动零
Leetcode:283. 移动零题目描述给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 示例:输入: [0,1,0,3,12] 输出: [1,3,12,0,0] 说明:必须在原数组上操作
2020-03-26
  目录