Ugly Number II
2015-08-22 05:48
169 查看
Write a program to find the
Ugly numbers are positive numbers whose prime factors only include
Note that
Analyse: We can divide the ugly numbers into three categories:
2: 1*2, 2*2, 3*2, 4*2, 5*2...
3: 1*3, 2*3, 3*3, 4*3, 5*3...
5: 1*5, 2*5, 3*5, 4*5, 5*5...
So our job is to find the first n number in these three arrays. If we already find the i-th smallest number, the next number should be min(l1*2, l2*3, l3*5). The point is that we need to mark the current position of the three arrays, which means that the factor that we want to multiply is the smallest one in the result array. Thus, if the element in one array is selected, then we increase this index.
Runtime: 8ms.
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.
Analyse: We can divide the ugly numbers into three categories:
2: 1*2, 2*2, 3*2, 4*2, 5*2...
3: 1*3, 2*3, 3*3, 4*3, 5*3...
5: 1*5, 2*5, 3*5, 4*5, 5*5...
So our job is to find the first n number in these three arrays. If we already find the i-th smallest number, the next number should be min(l1*2, l2*3, l3*5). The point is that we need to mark the current position of the three arrays, which means that the factor that we want to multiply is the smallest one in the result array. Thus, if the element in one array is selected, then we increase this index.
Runtime: 8ms.
class Solution { public: int nthUglyNumber(int n) { if(n <= 1) return n; const int len = n; int ugly = {1}; int l1 = 0, l2 = 0, l3 = 0;//to represent the current location of the arrays respectively int f1 = 2, f2 = 3, f3 = 5;//to represent the current ugly factors for(int i = 1; i < n; i++){ int least = min(min(f1, f2), f3); if(least == f1) { ugly[i] = f1; f1 = 2 * ugly[++l1]; } if(least == f2){ ugly[i] = f2; f2 = 3 * ugly[++l2]; } if(least == f3){ ugly[i] = f3; f3 = 5 * ugly[++l3]; } } return ugly[n - 1]; } };
相关文章推荐
- (转载)数据库表分割技术浅析(水平分割/垂直分割/库表散列)
- mysql视图
- mysql视图
- Unity Manual之Network 网络
- linux man命令使用详解
- LeetCode Reverse Linked List II
- LeetCode Reverse Linked List II
- POJ 1188 解题报告
- LeetCode_Surrounded Regions
- Atom编辑器折腾记_(15)JS代码片段补全(插件:javascript-snippets)
- Atom编辑器折腾记_(15)JS代码片段补全(插件:javascript-snippets)
- 在交互式shell脚本中创建对话框
- Atom编辑器折腾记_(14)JQ代码片段补全(插件:Jquery-snippets)
- Atom编辑器折腾记_(14)JQ代码片段补全(插件:Jquery-snippets)
- LeetCode Reverse Linked List
- Leetcode_Palindrome Partitioning II
- LeetCode Reverse Linked List
- [LeetCode#47]Permutations II
- shell脚本中一些特殊符号
- 使用wget 命令下载JDK的方法