LeetCode-Ugly Number II-解题报告
2015-08-28 15:52
651 查看
原链接https://leetcode.com/problems/ugly-number-ii/
Write a program to find the
Ugly numbers are positive numbers whose prime factors only include
For example,
numbers.
Note that
将包含一个数分解质因素后只有2,3,5中的数
如果一个数是ugly数 那么乘以2,3,5中的一个或多个,那么它也是ugly数
关键是如果从小到大依次求的
1肯定是ugly数
1*2 1*3 1*5 中最小的是2 所以下一个是2
1 2;
那么下一个个数是肯定是在 2*2 1*3 1*5 中的
所以 定义一个cnt[3],表示2,3,5该乘上ugly数组中的arr[cnt[0,1,2]];
如果对应的2,3,或者5为当前最小的,那么他的cnt应该++;
然而这并不能求出最终答案,应为可能出现相同的数
比如 2*3 3*2这种情况。
只需要在取出数字后判断是否可前面一个相等,相等继续循环,并且循环变量-1,也就是让下次继续求第i个ugly数,直到与前面一个不同。
class Solution {
public:
int nthUglyNumber(int n) {
int cnt[3] = { 0 };
int* arr = new int
;
arr[0] = 1;
for (int i = 1; i < n; ++i)
{
int pos = 0;
arr[i] = Min(arr[cnt[0]] * 2, arr[cnt[1]] * 3, arr[cnt[2]] * 5, pos);
if (arr[i] == arr[i - 1])i--;
cnt[pos]++;
}
return arr[n - 1];
}
inline int Min(int a, int b, int c, int& pos)
{
if (a > b)a = b, pos = 1;
if (a > c)a = c, pos = 2;
return a;
}
};
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.
将包含一个数分解质因素后只有2,3,5中的数
如果一个数是ugly数 那么乘以2,3,5中的一个或多个,那么它也是ugly数
关键是如果从小到大依次求的
1肯定是ugly数
1*2 1*3 1*5 中最小的是2 所以下一个是2
1 2;
那么下一个个数是肯定是在 2*2 1*3 1*5 中的
所以 定义一个cnt[3],表示2,3,5该乘上ugly数组中的arr[cnt[0,1,2]];
如果对应的2,3,或者5为当前最小的,那么他的cnt应该++;
然而这并不能求出最终答案,应为可能出现相同的数
比如 2*3 3*2这种情况。
只需要在取出数字后判断是否可前面一个相等,相等继续循环,并且循环变量-1,也就是让下次继续求第i个ugly数,直到与前面一个不同。
class Solution {
public:
int nthUglyNumber(int n) {
int cnt[3] = { 0 };
int* arr = new int
;
arr[0] = 1;
for (int i = 1; i < n; ++i)
{
int pos = 0;
arr[i] = Min(arr[cnt[0]] * 2, arr[cnt[1]] * 3, arr[cnt[2]] * 5, pos);
if (arr[i] == arr[i - 1])i--;
cnt[pos]++;
}
return arr[n - 1];
}
inline int Min(int a, int b, int c, int& pos)
{
if (a > b)a = b, pos = 1;
if (a > c)a = c, pos = 2;
return a;
}
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- C++ Custom Control控件向父窗体发送对应的消息
- C++中拷贝构造函数的应用详解