384. 打乱数组

140 阅读1分钟

题目:

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

实现 Solution class:

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

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/sh… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法: 多次shuffle,每次返回不同的洗牌结果,不同结果返回概率相同

import "math/rand"
type Solution struct {
	origin []int
}


func Constructor(nums []int) Solution {
	return Solution{nums}
}


func (this *Solution) Reset() []int {
	return this.origin
}


func (this *Solution) Shuffle() []int {
        // copy(dst,src) dst长度要先初始化好
	shuffle := make([]int, len(this.origin))
	copy(shuffle, this.origin)
	
	for i := 0; i < len(shuffle); i ++ {
		j := rand.Intn(len(shuffle))
		shuffle[i],shuffle[j] = shuffle[j],shuffle[i]
	}
	return shuffle
}