【剑指offer系列】 丑数___34
来源:互联网 发布:minecraft 源码 unity 编辑:程序博客网 时间:2024/06/06 13:56
题目描述:
我们把只包含因子2 、 3 、5的数称为丑数。
求按照从小到大的顺序输出第n个丑数,习惯上把1作为第一个丑数
分析:
1、我们可以通过遍历1到m个数,依次判断是否为丑数,直到找到第n个丑数
但是这种方法包含很多重复的判断,效率非常低
2、创建数组,依次保存已经找到的丑数。由于丑数都是由因子2、 3、 5生成的,因此可以方便的生成每个丑数
代码:
int nthUglyNumber(int n) { if(n<=0) return 0; int *num=new int[n]; num[0]=1; int *m2=num; int *m3=num; int *m5=num; int index=1; while(index<n){ int next=min((*m2)*2,min((*m3)*3,(*m5)*5)); num[index]=next; while((*m2)*2<=next) ++m2; while((*m3)*3<=next) ++m3; while((*m5)*5<=next) ++m5; ++index; } return num[n-1]; }
0 0
- 【剑指offer系列】 丑数___34
- 剑指offer系列源码-丑数
- 剑指offer系列之32:丑数
- 【剑指offer】丑数
- 剑指offer-丑数
- 《剑指offer》丑数
- 【剑指Offer】丑数
- 剑指offer:丑数
- 剑指offer-丑数
- [剑指offer]丑数
- 剑指offer:丑数
- [剑指offer]丑数
- 《剑指offer》-丑数
- 剑指offer----丑数
- 剑指offer|丑数
- 剑指offer-丑数
- 剑指Offer:丑数
- 剑指offer--丑数
- android之notifyDataSetChanged失效
- Ubuntu VSFTP的配置方法
- JSP中 Session和作用域的使用
- LeetCode *** 168. Excel Sheet Column Title
- java中复制数组的几种方式
- 【剑指offer系列】 丑数___34
- interleaving string
- 编写新闻客户端&网络编程day1(66期第四天)
- Vulkan Render Pass
- stash的hooks和api
- ios拨打电话
- 排序问题-希尔排序
- 第6周项目1-分数类的雏形(1)
- LeetCode 13 -Roman to Integer ( JAVA )