- 32.0%

https://leetcode.com/problems/ugly-number-ii

Write a program to find the 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, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number, and n does not exceed 1690.

Hint:

- The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones.
- An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
- The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3.
- Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1
*2, L2*3, L3 * 5).

方法一:

my code：

1 | class Solution { |

我的代码实现：

1 | class Solution { |

方法二:

36ms, 28.93%, May.3rd, 2016

https://leetcode.com/discuss/58186/elegant-c-solution-o-n-space-time-with-detailed-explanation

1 | class Solution { |

#### cpp

20ms, 44.77%, May.3rd, 2016

1 | class Solution { |

20ms, 44.77%, May.3rd, 2016

https://leetcode.com/discuss/53225/c-one-pass-simple-solution

1 | class Solution { |

#### python

212ms, 67.75%, May.3rd, 2016

https://leetcode.com/discuss/57156/my-expressive-python-solution

1 | class Solution(object): |

#### java

The idea of this solution is from this page:http://www.geeksforgeeks.org/ugly-numbers/

The ugly-number sequence is 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, …

because every number can only be divided by 2, 3, 5, one way to look at the sequence is to split the sequence to three groups as below:

1 | (1) 1×2, 2×2, 3×2, 4×2, 5×2, … |

We can find that every subsequence is the ugly-sequence itself (1, 2, 3, 4, 5, …) multiply 2, 3, 5.

Then we use similar merge method as merge sort, to get every ugly number from the three subsequence.

Every step we choose the smallest one, and move one step after,including nums with same value.

Thanks for this author about this brilliant idea. Here is my java solution

1 | public class Solution { |

my code

1 | public class Solution { |