LEETCode 264. Ugly Number II
2016-07-26 20:59
381 查看
问题描述:
Write a program to find the
Ugly numbers are positive numbers whose prime factors only include
Note that
找第N个丑数,最基础的从1开始判断的方法就不说了,此处的方法是剑指offer上的思路。从1开始遍历的方法复杂度太高,这里只需要考虑到从小到大的开始的每个丑数,都是他前面某个数的2或3或5倍,,因此从已有的丑数1出发,分别诚乘以2、3、5,找出其中最小的一个,得到第二个丑数为2,再找第三个丑数的时候,就要注意到到,由于1乘以2已经出现了,因此下一次是2*2,1*3,1*5,后面的逻辑类似。要注意的时,会出现下一个丑数同时满足多个条件。如6 满足 2*3 也满足3*2 此时 对应的都要更新,不能只更新第一个,所以代码中用的是三个if,而不能是if
、else if
AC代码如下:
int minThree(int x,int y,int z)
{
int temp = x < y ? x : y;
return temp < z ? temp : z;
}
int nthUglyNumber(int n)
{
int count = 0;
int *ugly = new int
;
memset(ugly,0,sizeof(int)*n);
int index1,index2,index3;
index1 = index2 = index3 = 0;
ugly[0] = 1;
while(count < n-1)
{
int No = minThree(2*ugly[index1],3*ugly[index2],5*ugly[index3]);
if(No == 2*ugly[index1])
{
index1++;
}
if(No == 3*ugly[index2])
{
index2++;
}
if(No == 5*ugly[index3])
{
index3++;
}
count++;
ugly[count] = No;
}
return ugly[count];
}
Write a program to find the
n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include
2, 3, 5. For example,
1, 2, 3, 4, 5, 6, 8, 9, 10, 12is the sequence of the first
10ugly numbers.
Note that
1is typically treated as an ugly number.
找第N个丑数,最基础的从1开始判断的方法就不说了,此处的方法是剑指offer上的思路。从1开始遍历的方法复杂度太高,这里只需要考虑到从小到大的开始的每个丑数,都是他前面某个数的2或3或5倍,,因此从已有的丑数1出发,分别诚乘以2、3、5,找出其中最小的一个,得到第二个丑数为2,再找第三个丑数的时候,就要注意到到,由于1乘以2已经出现了,因此下一次是2*2,1*3,1*5,后面的逻辑类似。要注意的时,会出现下一个丑数同时满足多个条件。如6 满足 2*3 也满足3*2 此时 对应的都要更新,不能只更新第一个,所以代码中用的是三个if,而不能是if
、else if
AC代码如下:
int minThree(int x,int y,int z)
{
int temp = x < y ? x : y;
return temp < z ? temp : z;
}
int nthUglyNumber(int n)
{
int count = 0;
int *ugly = new int
;
memset(ugly,0,sizeof(int)*n);
int index1,index2,index3;
index1 = index2 = index3 = 0;
ugly[0] = 1;
while(count < n-1)
{
int No = minThree(2*ugly[index1],3*ugly[index2],5*ugly[index3]);
if(No == 2*ugly[index1])
{
index1++;
}
if(No == 3*ugly[index2])
{
index2++;
}
if(No == 5*ugly[index3])
{
index3++;
}
count++;
ugly[count] = No;
}
return ugly[count];
}
相关文章推荐
- jquery的get,post和ajax方法的使用
- Session和Cookie的区别
- 对map集合进行排序
- HorizontalListView实现setSelection
- Codeforces 534C Polycarpus' Dice(思路)
- Leetcode no. 149
- JVM调优总结
- 搭建kafka集群
- scanf 用法及陷阱
- WebService基础学习(二)—三要素
- CSS盒子模型
- 【Python】map、filter、reduce函数简介
- 面试题53:正则表达式匹配
- HDOJ-----2199二分
- JavaWEB入门
- android ANR分析
- 读书笔记(一)_VC++深入详解
- 程序断点与数据断点
- CSS选择器
- MySQL(27):行锁、表锁、乐观锁、悲观锁