0数组/数学/随机化中等 LeetCode384. 打乱数组

384. 打乱数组

描述

给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。
实现 Solution class:
Solution(int[] nums) 使用整数数组 nums 初始化对象
int[] reset() 重设数组到它的初始状态并返回
int[] shuffle() 返回数组随机打乱后的结果

分析

难在如何生成一个随机排列。使用util工具类下面的Random类,生成一个随机数组下标。但如何确保这个随机数一定还是没有被选中的。
解决办法是“交换”,这样每个随即下标都是在还没有选中的元素里面选取的。
Random的nextInt(int bound)
生成一个均匀分布的值在0(包括)和指定值(不包括)之间的int值

class Solution {
    
    

    public int[] defaultArray;
    public int[] workArray;
    public Solution(int[] nums){
    
    
        this.workArray = nums;
        int[] tmp = new int[nums.length];
        for(int i = 0; i < nums.length; i++){
    
    
            tmp[i] = nums[i];
        }
        this.defaultArray = tmp;
    }

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

    public int[] shuffle(){
    
    
        int len = workArray.length;
        for(int i= 0; i < len; i++){
    
    
            swap(workArray,i, new Random().nextInt(len-i)+i);
        }
        return workArray;
    }
    
    public void swap(int[] nums, int i, int j){
    
    
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}

Guess you like

Origin blog.csdn.net/weixin_43260719/article/details/121473328