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

打乱数组(Java实现)

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

打乱数组(Java实现)

问题直通车

力扣 (LeetCode)
https://leetcode.cn/leetbook/read/top-interview-questions-easy/xn6gq1/

问题详述

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

实现Solution class:

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

  • 1 <= nums.length <= 50
  • -10^6 <= nums[i] <= 10^6
  • nums 中的所有元素都是 唯一的
  • 最多可以调用 104 次 reset 和 shuffle
我的解法

从后往前遍历数组,随机生成数组下标,将对应元素放到新数组中,然后将该元素交换至原数组末尾,然后继续循环生成数组下标(此时随机数范围已减一)

public class Solution {

    private int[] nums;
    private Random random;

    public Solution(int[] nums) {
        this.nums = nums;
        this.random = new Random();
    }

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

    public int[] shuffle() {
        if (nums == null) {
            return null;
        }
        int len = nums.length;
        int[] clone = nums.clone(); // 涉及数据交换,所以应操作克隆数组
        int[] newArray = new int[len];
        for (int i = len; i > 0; i--) {
            // 在数组中找随机下标数据,放入新数组
            int index = random.nextInt(i);
            newArray[i - 1] = clone[index];
            // 将下标对应数据与末尾数据进行交换
            swap(clone, index, i - 1);
        }
        return newArray;
    }

    public void swap(int[] a, int i, int j) {
        a[i] = a[i] + a[j];
        a[j] = a[i] - a[j];
        a[i] = a[i] - a[j];
    }

}

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

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

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