lintcode-medium-Ugly Number II
2016-04-07 06:13
423 查看
Ugly number is a number that only have factors
Design an algorithm to find the nth ugly number. The first 10 ugly numbers are
Notice
Note that
Example
If
Challenge
O(n log n) or O(n) time.
2,
3and
5.
Design an algorithm to find the nth ugly number. The first 10 ugly numbers are
1, 2, 3, 4, 5, 6, 8, 9, 10, 12...
Notice
Note that
1is typically treated as an ugly number.
Example
If
n=9, return
10.
Challenge
O(n log n) or O(n) time.
class Solution { /** * @param n an integer * @return the nth prime number as description. */ public int nthUglyNumber(int n) { // Write your code here if(n <= 0) return 0; ArrayList<Integer> res = new ArrayList<Integer>(); res.add(1); int cur = 1; int p1 = 0; int p2 = 0; int p3 = 0; int min1 = 1; int min2 = 1; int min3 = 1; while(res.size() < n){ while(res.get(p1) * 2 <= cur) p1++; min1 = res.get(p1) * 2; while(res.get(p2) * 3 <= cur) p2++; min2 = res.get(p2) * 3; while(res.get(p3) * 5 <= cur) p3++; min3 = res.get(p3) * 5; int next = Math.min(min1, Math.min(min2, min3)); res.add(next); cur = next; } return res.get(n - 1); } };
相关文章推荐
- 关于Windhow
- [LeetCode] Duplicate Emails 重复的邮箱
- LeetCode 246. Strobogrammatic Number
- LeetCode 245. Shortest Word Distance III(最短单词距离)
- The method getDispatcherType() is undefined for the type HttpServletRequest 升级到tomcat8(转)
- ios中的定时
- LeetCode 244. Shortest Word Distance II(最短单词距离)
- lintcode-easy-Ugly Number
- #8判断和循环#
- Xsolla 电子竞技学院合作项目正式启动:你加入了么?
- vs2015中升级Nuget后,找不到Umbraco安装包问题
- Windows的自带控件(比如TButton)大多数消息都由它自己处理,Delphi覆盖了那么多WM_函数优先级较低,一般用不上
- liunx 下scp出现 Permission denied, please try again 的解决办法
- Windows下Keras报错TypeError: <lambda>() got an unexpected keyword argument 'name'
- HttpClient
- Android属性动画
- swift 二维数组
- Nexus启动失败处理:The nexus service was launched, but failed to start.
- VB洗牌算法产生随机数组
- 五种情况下会刷新控件状态(刷新所有子FWinControls的显示)——从DFM读取数据时、新增加子控件时、重新创建当前控件的句柄时、设置父控件时、显示状态被改变时