LeetCode:打乱数组(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];
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值