Created
December 19, 2017 03:27
-
-
Save aquawj/fd71a1ab4fa434bafe5ef2b486917f5e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
处理random有两种方法: | |
1. Math.random() 生成[0,1)之间随机数 | |
2. Random类,可以调用不同方法 | |
Random 类中的方法比较简单,每个方法的功能也很容易理解。需要说明的是,Random类中各方法生成的随机数字都是均匀分布的,也就是说区间内部的数字生成的几率是均等的 | |
a 、public boolean nextBoolean() | |
该方法的作用是生成一个随机的boolean值,生成true和false的值几率相等,也就是都是50%的几率。 | |
b 、public double nextDouble() | |
该方法的作用是生成一个随机的double值,数值介于[0,1.0)之间,这里中括号代表包含区间端点,小括号代表不包含区间端点,也就是0到1之间的随机小数,包含0而不包含1.0。 | |
c 、public int nextInt() | |
该方法的作用是生成一个随机的int值,该值介于int的区间,也就是-2的31次方到2的31次方-1之间。 | |
如果需要生成指定区间的int值,则需要进行一定的数学变换,具体可以参看下面的使用示例中的代码。 | |
d 、public int nextInt(int n) | |
该方法的作用是生成一个随机的int值,该值介于[0,n)的区间,也就是0到n之间的随机int值,包含0而不包含n。 | |
如果想生成指定区间的int值,也需要进行一定的数学变换,具体可以参看下面的使用示例中的代码 | |
举例: | |
生成[1,2.5)区间的小数 double d3 = r.nextDouble() * 1.5 + 1; | |
class Solution { | |
Random r; | |
int[] nums; | |
public Solution(int[] nums) { | |
r = new Random(); | |
this.nums = nums; | |
} | |
public int pick(int target) { | |
int count = 0; | |
int index = -1; | |
for(int i = 0; i < nums.length; i++){ | |
if(nums[i] == target){ | |
count++; | |
if(r.nextInt(count) == 0){ //r.nextInt()返回一个任意int。r.nextInt(number)返回一个(0,number]之间的int | |
index = i; | |
} | |
} | |
} | |
return index; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment