[LeetCode]384. Shuffle an Array

本文介绍了一种使用原地洗牌算法实现数组随机排列的方法。通过从前往后遍历数组,并用随机数生成器选取已遍历部分的一个元素与当前元素进行交换,最终达到数组随机化的目的。文章提供了一个具体的Java实现示例。

https://leetcode.com/problems/shuffle-an-array/#/description

shuffle一个数组







从前往后遍历,随机取已经遍历过的位置里面一个数与当前遍历到的位置交换

public class Solution {
    
    int[] nums;
    Random random;

    public Solution(int[] nums) {
        this.nums = nums;
        random = new Random();
    }
    
    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        return nums;
    }
    
    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        if (nums == null) {
            return null;
        }
     // 又学一个api~
        int[] a = nums.clone();
        for (int i = 1; i < nums.length; i++) {
            int j = random.nextInt(i + 1);
            swap(a, i, j);
        }
        return a;
    }
    
    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值