LeetCode OJ:Ugly Number II(丑数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.
丑数问题,这一第n个应该按照顺序来数,这样可以使用一个set来维护顺序,直到数到第n个丑数:
1 class Solution { 2 public: 3 int nthUglyNumber(int n) { 4 set<long> ret; 5 long res; 6 ret.insert(1); 7 for(int i = 0; i < n; ++i){ 8 res = *ret.begin(); 9 ret.insert(res * 2); 10 ret.insert(res * 3); 11 ret.insert(res * 5); 12 ret.erase(res); 13 } 14 return (int)res; 15 } 16 };