产生 1-N的不重复的随机序列,可采用交换数据的思路;
1.首先(产生/确定)原始的数组(1-N)
2.交换数据,遍历数组,对数组第i项都要产生一个(0,i)的随机数与之交换
产生区间(i,j)的随机数,r.nextInt(0,j-i+1)+i;
java版本
class Solution {
int[] nums;
int[] copy;
public Solution(int[] nums) {
this.nums=nums;
int[] copy=new int[nums.length];
for(int i=0;i<nums.length;i++){
copy[i]=nums[i];
}
this.copy=copy;
}
public int[] reset() {
return this.copy;
}
public int[] shuffle() {
int[] nums=this.nums;
int n=nums.length,tmp=0;
for(int i=1;i<n;i++){
change(nums,i,randInt(0,i));
}
return nums;
}
public static int randInt(int i, int j){
Random r=new Random();
return r.nextInt(j-i+1) + i;
}
public void change(int[] nums, int i, int j){
int tmp=nums[i];
nums[i]=nums[j];
nums[j]=tmp;
}
}
Go版本
import(
"fmt"
"math/rand"
)
type Solution struct {
nums,copy []int
}
func Constructor(nums []int) Solution {
return Solution{nums, append([]int(nil), nums...)}
}
func (this *Solution) Reset() []int {
copy(this.nums, this.copy)
return this.nums
}
func (this *Solution) Shuffle() []int {
n:=len(this.nums);
for i,_ :=range this.nums{
j:=rand.Intn(n-i)+i;
this.nums[i],this.nums[j]=this.nums[j],this.nums[i];
}
return this.nums;
}
func change(nums []int,i int,j int){
tmp:=nums[i];
nums[i]=nums[j];
nums[j]=tmp;
}
网友评论