# Ugly Number
### Source
- leetcode: [Ugly Number | LeetCode OJ](https://leetcode.com/problems/ugly-number/)
- lintcode: [(4) Ugly Number](http://www.lintcode.com/en/problem/ugly-number/)
~~~
Ugly number is a number that only have factors 3, 5 and 7.
Design an algorithm to find the Kth ugly number.
The first 5 ugly numbers are 3, 5, 7, 9, 15 ...
Example
If K=4, return 9.
Challenge
O(K log K) or O(K) time.
~~~
### 题解1 - [TLE](# "Time Limit Exceeded 的简称。你的程序在 OJ 上的运行时间太长了,超过了对应题目的时间限制。")
Lintcode 和 Leetcode 中质数稍微有点区别,这里以 Lintcode 上的版本为例进行说明。寻找第 K 个丑数,丑数在这里的定义是仅能被3,5,7整除。简单粗暴的方法就是挨个检查正整数,数到第 K 个丑数时即停止。
### Java
~~~
class Solution {
/**
* @param k: The number k.
* @return: The kth prime number as description.
*/
public long kthPrimeNumber(int k) {
if (k <= 0) return -1;
int count = 0;
long num = 1;
while (count < k) {
num++;
if (isUgly(num)) {
count++;
}
}
return num;
}
private boolean isUgly(long num) {
while (num % 3 == 0) {
num /= 3;
}
while (num % 5 == 0) {
num /= 5;
}
while (num % 7 == 0) {
num /= 7;
}
return num == 1;
}
}
~~~
### 源码分析
判断丑数时依次约掉质因数3,5,7,若处理完所有质因数3,5,7后不为1则不是丑数。自增 num 时应在判断是否为丑数之前。
### 复杂度分析
无法准确分析,但是估计在 O(n3)O(n^3)O(n3) 以上。
### 题解2 - 二分查找
根据丑数的定义,它的质因数只含有3, 5, 7, 那么根据这一点其实可以知道后面的丑数一定可以从前面的丑数乘3,5,7得到。那么可不可以将其递推关系用数学公式表示出来呢?
我大概做了下尝试,首先根据丑数的定义可以写成 Uk=3x3⋅5x5⋅7x7U_k = 3^{x_3} \cdot 5^{x_5} \cdot 7^{x_7}Uk=3x3⋅5x5⋅7x7, 那么 Uk+1U_{k+1}Uk+1 和 UkU_kUk 的不同则在于 x3,x5,x7x_3, x_5, x_7x3,x5,x7 的不同,递推关系为 Uk+1=Uk⋅3y3⋅5y5⋅7y73z3⋅5z5⋅7z7U_{k+1} = U_k \cdot \frac{3^{y_3} \cdot 5^{y_5} \cdot 7^{y_7}}{3^{z_3} \cdot 5^{z_5} \cdot 7^{z_7}}Uk+1=Uk⋅3z3⋅5z5⋅7z73y3⋅5y5⋅7y7,将这些分数按照从小到大的顺序排列可在 O(K)O(K)O(K) 的时间内解决,但是问题来了,得到这些具体的 y,zy, zy,z 就需要费不少时间,且人工操作极易漏解。:( 所以这种解法只具有数学意义,没有想到好的实现方法。
除了这种找相邻递推关系的方法我们还可以尝试对前面的丑数依次乘3, 5, 7,直至找到比当前最大的丑数大的一个数,对乘积后的三种不同结果取最小值即可得下一个最大的丑数。这种方法需要保存之前的 N 个丑数,由于已按顺序排好,天然的二分法。
### Java
~~~
class Solution {
/**
* @param k: The number k.
* @return: The kth prime number as description.
*/
public long kthPrimeNumber(int k) {
if (k <= 0) return -1;
ArrayList<Long> nums = new ArrayList<Long>();
nums.add(1L);
for (int i = 0; i < k; i++) {
long minNextUgly = Math.min(nextUgly(nums, 3), nextUgly(nums, 5));
minNextUgly = Math.min(minNextUgly, nextUgly(nums, 7));
nums.add(minNextUgly);
}
return nums.get(nums.size() - 1);
}
private long nextUgly(ArrayList<Long> nums, int factor) {
int size = nums.size();
int start = 0, end = size - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums.get(mid) * factor > nums.get(size - 1)) {
end = mid;
} else {
start = mid;
}
}
if (nums.get(start) * factor > nums.get(size - 1)) {
return nums.get(start) * factor;
}
return nums.get(end) * factor;
}
}
~~~
### 源码分析
`nextUgly`根据输入的丑数数组和 factor 决定下一个丑数,`nums.add(1L)`中1后面需要加 L表示 Long, 否则编译错误。
### 复杂度分析
找下一个丑数 O(logK)O(\log K)O(logK), 循环 K 次,故总的时间复杂度近似 O(KlogK)O(K \log K)O(KlogK), 使用了数组保存丑数,空间复杂度 O(K)O(K)O(K).
### 题解3 - 动态规划
TBD
### Reference
- 《剑指 Offer》第五章
- [Ugly Numbers - GeeksforGeeks](http://www.geeksforgeeks.org/ugly-numbers/)
- Preface
- Part I - Basics
- Basics Data Structure
- String
- Linked List
- Binary Tree
- Huffman Compression
- Queue
- Heap
- Stack
- Set
- Map
- Graph
- Basics Sorting
- Bubble Sort
- Selection Sort
- Insertion Sort
- Merge Sort
- Quick Sort
- Heap Sort
- Bucket Sort
- Counting Sort
- Radix Sort
- Basics Algorithm
- Divide and Conquer
- Binary Search
- Math
- Greatest Common Divisor
- Prime
- Knapsack
- Probability
- Shuffle
- Basics Misc
- Bit Manipulation
- Part II - Coding
- String
- strStr
- Two Strings Are Anagrams
- Compare Strings
- Anagrams
- Longest Common Substring
- Rotate String
- Reverse Words in a String
- Valid Palindrome
- Longest Palindromic Substring
- Space Replacement
- Wildcard Matching
- Length of Last Word
- Count and Say
- Integer Array
- Remove Element
- Zero Sum Subarray
- Subarray Sum K
- Subarray Sum Closest
- Recover Rotated Sorted Array
- Product of Array Exclude Itself
- Partition Array
- First Missing Positive
- 2 Sum
- 3 Sum
- 3 Sum Closest
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array II
- Merge Sorted Array
- Merge Sorted Array II
- Median
- Partition Array by Odd and Even
- Kth Largest Element
- Binary Search
- Binary Search
- Search Insert Position
- Search for a Range
- First Bad Version
- Search a 2D Matrix
- Search a 2D Matrix II
- Find Peak Element
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array II
- Find Minimum in Rotated Sorted Array
- Find Minimum in Rotated Sorted Array II
- Median of two Sorted Arrays
- Sqrt x
- Wood Cut
- Math and Bit Manipulation
- Single Number
- Single Number II
- Single Number III
- O1 Check Power of 2
- Convert Integer A to Integer B
- Factorial Trailing Zeroes
- Unique Binary Search Trees
- Update Bits
- Fast Power
- Hash Function
- Count 1 in Binary
- Fibonacci
- A plus B Problem
- Print Numbers by Recursion
- Majority Number
- Majority Number II
- Majority Number III
- Digit Counts
- Ugly Number
- Plus One
- Linked List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List II
- Remove Duplicates from Unsorted List
- Partition List
- Two Lists Sum
- Two Lists Sum Advanced
- Remove Nth Node From End of List
- Linked List Cycle
- Linked List Cycle II
- Reverse Linked List
- Reverse Linked List II
- Merge Two Sorted Lists
- Merge k Sorted Lists
- Reorder List
- Copy List with Random Pointer
- Sort List
- Insertion Sort List
- Check if a singly linked list is palindrome
- Delete Node in the Middle of Singly Linked List
- Rotate List
- Swap Nodes in Pairs
- Remove Linked List Elements
- Binary Tree
- Binary Tree Preorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal II
- Maximum Depth of Binary Tree
- Balanced Binary Tree
- Binary Tree Maximum Path Sum
- Lowest Common Ancestor
- Invert Binary Tree
- Diameter of a Binary Tree
- Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal
- Subtree
- Binary Tree Zigzag Level Order Traversal
- Binary Tree Serialization
- Binary Search Tree
- Insert Node in a Binary Search Tree
- Validate Binary Search Tree
- Search Range in Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Binary Search Tree Iterator
- Exhaustive Search
- Subsets
- Unique Subsets
- Permutations
- Unique Permutations
- Next Permutation
- Previous Permuation
- Unique Binary Search Trees II
- Permutation Index
- Permutation Index II
- Permutation Sequence
- Palindrome Partitioning
- Combinations
- Combination Sum
- Combination Sum II
- Minimum Depth of Binary Tree
- Word Search
- Dynamic Programming
- Triangle
- Backpack
- Backpack II
- Minimum Path Sum
- Unique Paths
- Unique Paths II
- Climbing Stairs
- Jump Game
- Word Break
- Longest Increasing Subsequence
- Palindrome Partitioning II
- Longest Common Subsequence
- Edit Distance
- Jump Game II
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock IV
- Distinct Subsequences
- Interleaving String
- Maximum Subarray
- Maximum Subarray II
- Longest Increasing Continuous subsequence
- Longest Increasing Continuous subsequence II
- Graph
- Find the Connected Component in the Undirected Graph
- Route Between Two Nodes in Graph
- Topological Sorting
- Word Ladder
- Bipartial Graph Part I
- Data Structure
- Implement Queue by Two Stacks
- Min Stack
- Sliding Window Maximum
- Longest Words
- Heapify
- Problem Misc
- Nuts and Bolts Problem
- String to Integer
- Insert Interval
- Merge Intervals
- Minimum Subarray
- Matrix Zigzag Traversal
- Valid Sudoku
- Add Binary
- Reverse Integer
- Gray Code
- Find the Missing Number
- Minimum Window Substring
- Continuous Subarray Sum
- Continuous Subarray Sum II
- Longest Consecutive Sequence
- Part III - Contest
- Google APAC
- APAC 2015 Round B
- Problem A. Password Attacker
- Microsoft
- Microsoft 2015 April
- Problem A. Magic Box
- Problem B. Professor Q's Software
- Problem C. Islands Travel
- Problem D. Recruitment
- Microsoft 2015 April 2
- Problem A. Lucky Substrings
- Problem B. Numeric Keypad
- Problem C. Spring Outing
- Microsoft 2015 September 2
- Problem A. Farthest Point
- Appendix I Interview and Resume
- Interview
- Resume