import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* @author: nanjing0412
* @date: 2021/11/28
* @description:
*/
public class Solution {
public static void main(String[] args) {
//随机输出0到n-1的数字,不重复,概率相等,可用于抽奖或洗牌
call(10);
}
private static Random random = new Random();
private static Map<Integer, Integer> map = new HashMap<>();
private static int size;
private static void call(int _size) {
size = _size;
while(size >= 1) {
System.out.println(random());
}
}
private static int random() {
// 随机得到的值
int x = random.nextInt(size--);
// 真正用的值
int y = map.getOrDefault(x, x);
// 对当前随机值,从右端点取一个值做映射,避免重复,妙!
map.put(x, map.getOrDefault(size, size));
return y;
}
}
根据leetcode,#519题目(随机翻转矩阵),有感得到的算法。