左神牛课网讲座第二发 算法讲解

从5随机到7随机及其扩展
【题目】 给定一个等概率随机产生1~5的随机函数rand1To5如下: public int rand1To5() {
return (int) (Math.random() * 5) + 1; }
除此之外不能使用任何额外的随机机制,请用rand1To5实现等概率随机产生1~7的随机函数rand1To7。 【补充题目】
给定一个以p概率产生0,以1-p概率产生1的随机函数rand01p如下:
public int rand01p() {
// you can change p as you like double p = 0.83;
return Math.random() < p ? 0 : 1;
} 除此之外不能使用任何额外的随机机制,请用rand01p实现等概率随机产生1~6的随机函数rand1To6。 【进阶题目】
给定一个等概率随机产生1~M的随机函数rand1ToM如下:
public int rand1ToM(int m) {
return (int) (Math.random() * m) + 1; }
除此之外不能使用任何额外的随机机制。有两个输入参数分别为m和n,请用rand1ToM(m)实现等概率随机产生1~n的随机函数 rand1ToN。
【题目】
1. publicintrand1To5(){
2. return (int) (Math.random() * 5) + 1;
3. }
4.
5. publicintrand1To7(){
6. intnum=0;
7. do{
8. num = (rand1To5() - 1) * 5 + rand1To5() - 1;
9. } while (num > 20);
10. returnnum%7+1;
11. }
【题目】 给定一个无序数组arr,求出需要排序的最短子数组长度。 例如:
arr = [1,5,3,4,2,6,7] 返回4,因为只有[5,3,4,2]需要排序。
【解】: 时间复杂度: O(n) 额外空间复杂度: O(1)
先左→右,找出max
再右→左,找min 因为求的是需要排序的最短子数组长度。
1. 2. 3. 4. 5. 6. 7. 8. 9.
10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21.
publicintgetMinLength(int[]arr){ if (arr == null || arr.length < 2) {
return 0; }
int min = arr[arr.length - 1];
int noMinIndex = -1; for(inti=arr.length-2;i!=-1;i--){
if (arr[i] > min) { noMinIndex = i;
}else{
min = Math.min(min, arr[i]);
} }
if (noMinIndex == -1) { return 0;
}
int max = arr[0];
int noMaxIndex = -1;
for (int i = 1; i != arr.length; i++) {
if (arr[i] < max) { noMaxIndex = i;22. 23. 24. 25. 26. 27.
}else{
max = Math.max(max, arr[i]);
} }
return noMaxIndex - noMinIndex + 1; }

 

posted @ 2015-08-11 15:00  微博和csdn还有你  阅读(154)  评论(0编辑  收藏  举报