每日打卡

2021-11-22 384. 打乱数组

2021-11-22  本文已影响0人  16孙一凡通工

产生 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;
}
上一篇 下一篇

猜你喜欢

热点阅读