(Java) LeetCode 470. Implement Rand10() Using Rand7() —— 用 Rand7() 实现 Rand10()
2018-08-07 17:48
806 查看
原文链接:https://www.geek-share.com/detail/2744635280.html
Given a function
rand7which generates a uniform random integer in the range 1 to 7, write a function
rand10which generates a uniform random integer in the range 1 to 10.
Do NOT use system's
Math.random().
Example 1:
Input: 1 Output: [7]
Example 2:
Input: 2 Output: [8,4]
Example 3:
Input: 3 Output: [8,1,10]
Note:
rand7
is predefined.- Each testcase has one argument:
n
, the number of times thatrand10
is called.
Follow up:
- What is the expected value for the number of calls to
rand7()
function? - Could you minimize the number of calls to
rand7()
?
一看就不会系列…不过还是在网上找到了思路。关键是如何利用rand7()等概率的生成1~10的数字。rand7()能做什么?等概率的生成1~7。但其实进阶一步也可以等概率的生成1~x,其中x是任意不大于7的数。具体做法就是先用rand7()生成一个1~7的数,之后舍弃大于x的数。于是乎,舍弃7的话就可以等概率生成1~6,就等于等概率生成0或1,只要对2取余就好。之后同样的方法舍弃6,7就可以等概率的生成1~5。两个结合在一起,如果第一步生成的是0,那么直接返回第二步的数(1~5);如果第一步生成的是1,那么返回第二步的数+5(6~10)。因为生成第一步生成0或1等概率,第二步生成1~5亦等概率,所以最后组合起来1~10依然等概率。
而至于这么做为什么不是最优解,还看这个文章及其下面的评论。https://leetcode.com/articles/implement-rand10-using-rand7/
Java
/** * 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 { private int oddOrEven() { int num = 0; while ((num = rand7()) > 6); return num % 2; } private int smallerOrBiggerThan5() { int num = 0; while ((num = rand7()) > 5); return num; } public int rand10() { int num1 = oddOrEven(); int num2 = smallerOrBiggerThan5(); if (num1 == 1) return num2 + 5; else return num2; } }
转载于:https://www.cnblogs.com/tengdai/p/9438422.html
相关文章推荐
- (Java) LeetCode 470. Implement Rand10() Using Rand7() —— 用 Rand7() 实现 Rand10()
- [LeetCode] Implement Rand10() Using Rand7() 使用Rand7()来实现Rand10()
- LeetCode OJ平台上Binary Tree Inorder Traversal题目使用java堆栈方式实现
- LeetCode 之 LRU Cache Java实现
- 【LeetCode-面试算法经典-Java实现】【056-Merge Intervals(区间合并)】
- Leetcode OJ平台上的Binary Tree Preorder Traversal题目用java ArrayDeque实现
- 【LeetCode-面试算法经典-Java实现】【010-Regular Expresssion Matching(正则表达式匹配)】
- 【LeetCode-面试算法经典-Java实现】【053-Maximum Subarray(最大子数组和)】
- 【LeetCode-面试算法经典-Java实现】【083-Remove Duplicates from Sorted List(排序的单链表中删除重复的结点)】
- leetcode题--Java实现
- LeetCode-java实现-T2-Add Two Numbers
- 【LeetCode-面试算法经典-Java实现】【014-Longest Common Prefix(最长公共前缀)】
- 【LeetCode-面试算法经典-Java实现】【028-Implement strStr() (实现strStr()函数)】
- 【LeetCode-面试算法经典-Java实现】【077-Combinations(组合数)】
- 【LeetCode-面试算法经典-Java实现】【078-Subsets(子集)】
- 【LeetCode-面试算法经典-Java实现】【092-Reverse Linked List II(反转单链表II)】
- 【LeetCode-面试算法经典-Java实现】【102-Binary Tree Level Order Traversal(二叉树层序遍历)】
- 【Leetcode】Sort List JAVA实现
- 153.Find Minimum in Rotated Sorted Array [LeetCode Java实现]
- LeetCode-java实现-T1-Two Sum