一. 随机数生成方法
(1)new Random()
Random r = new Random();
r.nextInt(100);//生成0-100内的随机数
(2)Math.random()
范围在 [0,1),如需要整型需要转成int使用
(3)currentTimeMillis()
long型,需要取余,也就是对随机数的范围取,比如(0-100),先%100,再转int
二. 随机数应用(leetcode实战)
给定一个可能含有重复元素的整数数组,要求随机输出给定的数字的索引。 您可以假设给定的数字一定存在于数组中。
class Solution {
HashMap<Integer,List<Integer>> map = new HashMap<>();
public Solution(int[] nums) {
for(int i = 0; i < nums.length; i++){
if(!map.containsKey(nums[i])){
List<Integer> list = new ArrayList<>();
list.add(i);