栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java打乱数组leetcode

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java打乱数组leetcode

        给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。打乱后,数组的所有排列应该是 等可能 的。

实现 Solution class:

Solution(int[] nums) 使用整数数组 nums 初始化对象
int[] reset() 重设数组到它的初始状态并返回
int[] shuffle() 返回数组随机打乱后的结果

class Solution {

    int[] num;
    int len;
    Random random = new Random();

    public Solution(int[] nums) {
        this.num = nums;
        this.len = nums.length;
    }
    
    public int[] reset() {
        return this.num;
    }
    
    public int[] shuffle() {
        int[] clone = num.clone();
        for(int i = 0;i < len;i++){
            swap(clone,i,i+random.nextInt(len-i));
        }
        return clone;
    }
    public void swap(int[] nums,int i ,int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

执行用时:49 ms, 在所有 Java 提交中击败了96.23%的用户

内存消耗:47.3 MB, 在所有 Java 提交中击败了86.73%的用户

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/851413.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号