简洁网站设计欣赏,9377霸主传奇网页版,温州易富信息技术有限公司,wordpress上传源代码文章目录题目描述代码 思路更新版三刷 - 极简版题目描述
貌似是比较高频的面试题目啊#xff0c;有学概率论内味了#xff08;讲道理我概率论学得不好#xff09;
代码 思路
先用Rand7实现RandN#xff08;N 10#xff09;#xff0c;类似进制…
文章目录题目描述代码 思路更新版三刷 - 极简版题目描述
貌似是比较高频的面试题目啊有学概率论内味了讲道理我概率论学得不好
代码 思路
先用Rand7实现RandNN 10类似进制本题N 7 * 7如果要求Rand50的话N就等于 7 * 7 * 7了以此类推。然后用RandN来实现Rand10()。总体思路就是这样更多还是看具体代码 注释吧
/*** The rand7() API is already defined in the parent class SolBase.* public int rand7();* return a random integer in the range 1 to 7*/
class Solution extends SolBase {public int rand10() {while(true){// ans 范围 [0, 48]其中各个值都是等概率的相当于用两次rand7()来实现二位的七进制树的十位和个位// 满足魔法值规范// 最大的区间上限值int maxNumLowIndex 40;// 目标进制int targetJZ 10;// 当前进制int nowJZ 7;// 等概率分成[0,9] [10, 19] [20, 29] [30, 39]而[40, 48]只能舍弃不够10位int ans (rand7() - 1) * nowJZ (rand7() - 1);if(ans maxNumLowIndex){// 把四个可行区间归一化成个位数然后再加1变成目标值。return ans % targetJZ 1;}}}
}更新版
-1、1为了规范范围能取到1%用于分割区间比如[0, 9] [10, 19]
class Solution extends SolBase {public int rand10() {int top 40;int now 7;int hope 10;while(true) {int ans (rand7() - 1) * now (rand7() - 1);if(ans top) {return ans % hope 1;}}}
}三刷 - 极简版
两行解决的事…
class Solution extends SolBase {public int rand10() {while(true) {int res (rand7() - 1) * 7 (rand7() - 1);if(res 40) return res % 10 1;}}
}