丑数
来源:互联网 发布:期指持仓数据 编辑:程序博客网 时间:2024/04/28 11:23
1.问题描述
我们把只包含因子2,3和5的数称作丑数。求按从小到大顺序的第1500个丑数。例如6,8都是丑数,但14不是,因为它包含因子7.习惯上我们把1当做第一个丑数。(来自《剑指offer》)
2.分析
我们设置一个数组,这里面保存着排好序的丑数,因为丑数是按顺序存放在数组中的。对乘以2而言,肯定存在某一个丑数T2,排在它之前的每一个丑数乘以2得到的结果都会小于已有的最大的丑数,在它之后的每一个丑数乘以2得到的结果都会太大。我们只需要记下这个丑数的位置,同时每次生成新的丑数的时候去更新这个T2,对乘以 3 和5而言也同样存在着T3和T5.
3.代码
int Min(int one,int two,int three){ int min = one; if (min > two) { min = two; } if (min > three) { min = three; } return min;}int GetUglyNumber(int index){ if (index <= 0) { return 0; } int uglyNumber[index]; uglyNumber[0] = 1; int nextUglyIndex = 1; int *mutiplay2 = uglyNumber; int *mutiplay3 = uglyNumber; int *mutiplay5 = uglyNumber; while (nextUglyIndex < index) { int min = Min(*mutiplay2 * 2,*mutiplay3 * 3,*mutiplay5 * 5); uglyNumber[nextUglyIndex] = min; while (*mutiplay2 * 2 <= uglyNumber[nextUglyIndex]) { mutiplay2++; } while (*mutiplay3 * 3 <= uglyNumber[nextUglyIndex]) { mutiplay3++; } while (*mutiplay5 * 5 <= uglyNumber[nextUglyIndex]) { mutiplay5++; } nextUglyIndex++; } return uglyNumber[index - 1]; }
0 0
- 丑数
- 丑数
- 丑数
- 丑数
- 丑数
- 丑数
- 丑数
- 丑数
- 丑数
- 丑数
- 丑数
- 丑数
- 丑数
- 丑数
- 丑数
- 丑数
- 丑数
- 丑数
- Remove Nth Node From End of List
- 2015.2.1号工作日志---------------赵鑫
- CDLinux 系统 破解WIFI密码 U盘 的制作(网卡:博通BCM4313)
- struts报错Can not find the tag library descriptor for "struts-tags"
- oracle 序列
- 丑数
- 【BZOJ2594】 Wc2006 水管局长数据加强版 Link-Cut-Tree
- HDU2549 壮志难酬【水题】
- 【操作系统】2、进程管理与死锁
- 汇编指令
- 第四周
- 【UML】图总述机房收费系统
- java连接sqlserver出错
- 经典网页设计:20个新鲜出炉的 HTML5 网站