LeetCode #384 打乱数组 Java 实现

LeetCode #384: 使用Java随机打乱数组
该博客介绍了如何使用Java实现LeetCode第384题的解决方案,包括两种方法:一是利用`java.util.Collections.shuffle()`进行数组打乱;二是通过`java.util.Random.nextInt()`实现等概率选取元素到数组的不同位置,确保不重复。

题目描述

打乱一个没有重复元素的数组。

// 以数字集合 1, 2 和 3 初始化数组。
int[] nums = {1,2,3};
Solution solution = new Solution(nums);

// 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。
solution.shuffle();

// 重设数组到它的初始状态[1,2,3]。
solution.reset();

// 随机返回数组[1,2,3]打乱后的结果。
solution.shuffle();

解决方案

三本水平——利用 java.util.Collections.shuffle()

注意基本类型数组和包装类对象数组之间的转换就好了,计算效率慢;

import java.util.*;

class Solution {

    private int[] originNums;
    private ArrayList<Integer> numList;
    public Solution(int[] nums) {
        originNums = nums;
    }
    
    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        return originNums;
    }
    
    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        numList = new ArrayList<Integer>(originNums.length);
        for(int num : originNums) {
            numList.add(num);
        }
        Collections.shuffle(numList);
        return makeDumbResult(numList);
    }
    
    public int[] makeDumbResult(List<Integer> numList) {
        int[] result = new int[numList.size()];
        for (int i=0;i<numList.size();i++) {
            result[i] = numList.get(i);
        }
        return result;
    }
}

一本水平——java.util.Random.nextInt 等概率选取

一个元素等概率地选择在数组中出现的位置,且不会重复出现两次及以上。
等概率随机算法的理论推导跟蓄水池算法1十分相似,代码十分简单且高效。

import java.util.*;

class Solution {
    private int[] start;
    private int[] exe;
    private int len;
    public Solution(int[] nums) {
        start = nums;
        exe = start.clone();
        len = exe.length;
    }
    
    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        return start;
    }
    
    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        Random r = new Random();
        int n = len;
        // 等概率选取算法核心
        while(n>1) {
            n--;
            int k = r.nextInt(n+1);
            int value = exe[k];
            exe[k] = exe[n];
            exe[n] = value;
        }
        return exe;
    }
}

  1. 蓄水池抽样算法——摘抄与问题扩展: https://blog.youkuaiyun.com/landstream/article/details/97051955 ↩︎

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值