384. 打乱数组 mark

题目

很有意思的题目,笔记看注释

掌握解法2,洗牌算法:遍历数组,每次选一个下标,将元素和当前下标元素交换(可以选到自己,保证概率相等),之后下标加1,继续遍历直到结束

截图自官方

 

解法1代码

class Solution {
    // 解法1
    // 这个生成随机数来模拟摸球的思路十分有意思。
    // 题目采取的是袋中先后顺序摸球来形成一个随机排列(保证概率相等)。
    // 官方题解表示当数组元素很多时,有n!种排列,需要lg (n!)比特来保证枚举到每一个排列
    // 因此,我们用一个list来模拟装满n个球的袋子,只需要用内置随机数先后生成n个数就行
    int[] save;
    int[] nums;
    public Solution(int[] nums) {
        // 数组克隆之后是一个全新的地址,互不干涉。
        save=nums.clone();
        // 注意这里必须深拷贝,要不都指向的是一个
        this.nums=nums;
    }
    // 看题解的意思
    public List<Integer> getCopyArray(){
        List<Integer> list=new ArrayList();
        for(int i=0;i<nums.length;i++){
               list.add(save[i]); 
        }
        return list;
    }
    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        // 本体这样就过了
        // return save;
        // 如果 重设到起源状态是指nums要还原
        nums=save;
        save=save.clone();
        return nums;
    }
    
    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        List<Integer> list=getCopyArray();
        Random random=new Random();
        for(int i=0;i<nums.length;i++){
            // 这里模拟袋子中每次摸了之后少一个球
            int getIndex=random.nextInt(list.size());
            nums[i]=list.get(getIndex);
            // 索引会自动从0排列
            list.remove(getIndex);
        }
        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();
 */

 

解法2代码

经典的洗牌算法

class Solution {

// 解法2,洗牌算法经典,效率更好,时空复杂度都是O(n),解法1时间复杂度是O(n^2)
    int[] save;
    int[] nums;
    public Solution(int[] nums) {
        save=nums.clone();
        this.nums=nums;
    }
    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        nums=save;
        save=save.clone();
        return nums;
    }
    public void swap(int a,int b){
        int temp=nums[a];
        nums[a]=nums[b];
        nums[b]=temp;
    }
    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        Random random=new Random();
            // 注意每次洗牌时当然可以“恰巧”选到自己,和自己交换
            for(int i=0;i<nums.length;i++){
                int target=random.nextInt(nums.length-i)+i;
                swap(i,target);
            }
            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();
 */

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值