《剑指offer》-寻找第n个丑数
2018-01-26 09:41
435 查看
/* * 把只包含因子2、3和5的数称作丑数(Ugly Number)。 * 例如6、8都是丑数,但14不是,因为它包含因子7。 * 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。 */ public class GetUglyNumber_Solution { //暴力搜索,算法超时 public int getUglyNumber_Solution(int index) { int count = 0; int result = 0; for(int i = 1;;i ++) { if(isUglyNumber(i)) { count ++; } if(count >= index) { result = i; break; } } return result; } public static boolean isUglyNumber(int n) { boolean flag = true; for(int i = 2;i <= n;i ++) { //i == n 也就是自身这一个也要考虑,若不考虑,则7也是丑数了 if(n % i == 0) { //不在2,3,5之列,或者不是他们的倍数 if(i % 2 != 0) { if(i % 3 != 0) { if(i % 5 != 0) { flag = false; break; } } } } } return flag; } //精简算法:利用初始的丑数来生成另一部分丑数,无需判断一个数是否为丑数,减小了算法复杂度 public int getUglyNumber_Solution2(int index) { if(index < 7) return index; int[] result = new int[index]; result[0] = 1; int index2 = 0; int index3 = 0; int index5 = 0; for(int i = 1;i < index;i ++) { result[i] = compare(result[index2] * 2, compare(result[index3] * 3, result[index5] * 5)); if(result[i] == result[index2] * 2) { //用过了指针就加一 index2 ++; } if(result[i] == result[index3] * 3) { index3 ++; } if(result[i] == result[index5] * 5) { index5 ++; } } return result[index - 1]; } public static int compare(int x, int y) { return x > y ? y : x; } public static void main(String[] args) { System.out.println(new GetUglyNumber_Solution().getUglyNumber_Solution(8)); } }
相关文章推荐
- 264.leetcode Ugly Number II(medium)[寻找第N个丑数]
- Ugly Number II 寻找第N个丑数
- 【剑指Offer-时间效率平衡】寻找第N个丑数
- 剑指offer 面试题34:寻找丑数(Leetcode 263.ugly number)解题报告
- 面试题:寻找第N个丑数
- 剑指offer面试题之求第n个丑数
- 剑指Offer---寻找第N个丑数
- 剑指offer系列之三十二:寻找丑数
- (剑指offer)丑数 寻找第一个只出现一次的字符
- 【编程题目】寻找丑数
- 找到第N个丑数
- 剑指offer:(34)时间效率和空间效率的平衡 :丑数
- 寻找丑数
- 寻找第K个丑数
- 寻找丑数
- 寻找丑数
- 程序员面试题精选100题(37)-寻找丑数
- 寻找丑数
- poj1338 寻找丑数
- Ugly Number 寻找丑数 简单题