Ugly Number II
2015-11-14 20:30
429 查看
题目描述
Write a program to find the n-th ugly number.题目解答
解题思路
Merge Sort的扩展题 每次选取最小的数需要暂存所有丑数, 并且需要处理重复的问题
丑数如下:
1, 2, 3, 4, 5, 6, 8, 10 ………….
规律:
1*2 2*2 3*2 4*2 5*2 6*2 8*2 10*2 ………….. *2
1*3 2*3 3*3 4*3 5*3 6*3 8*3 10*3 ………….. *3
1*5 2*5 3*5 4*5 5*5 6*5 8*5 10*5 ………….. *5
代码实现
public class Solution { public int nthUglyNumber(int n) { if(n <= 0) return -1; ArrayList<Integer> list = new ArrayList<>(); list.add(1); int p2 = 0, p3 = 0, p5 = 0; while(list.size() < n){ int uglyP2 = list.get(p2)*2, uglyP3 = list.get(p3)*3, uglyP5 = list.get(p5)*5; int min = Math.min(Math.min(uglyP2, uglyP3), uglyP5); if(min == uglyP2) p2++; if(min == uglyP3) p3++; if(min == uglyP5) p5++; //不用添加重复的元素 if(min != list.get(list.size() - 1)) list.add(min); } return list.get(n - 1); } }
相关文章推荐
- iar for 8051 v8.30破解文件的使用
- 70 Climbing Stairs
- Codeforces Round #328 (Div. 2) D. Super M
- OC协议的应用-代理
- 伪目标
- JavaScript之再谈回调与闭包
- iOS性能优化:Instruments使用实战
- 83 Remove Duplicates from Sorted List
- 时序图学习笔记
- 《大道至简》软件工程
- iOS9的新特性以及适配方案
- 论PHP常见的漏洞
- Educational Codeforces Round 1
- Android Studio编译好的apk放在哪里
- HTML 文本格式化
- 169 Majority Element
- 191 Number of 1 Bits
- 8086内存分段理解
- unity 在移动平台中,文件操作路径详解
- 虚拟串口软件和串口调试助手的简单使用