Ugly Number IIthis
Write a program to find the n
-th ugly number.spa
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.code
Note that 1
is typically treated as an ugly number.blog
Show Hint 排序
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.ci
思路:全部的ugly number都是由1開始,乘以2/3/5生成的。leetcode
只要將這些生成的數排序便可得到,自動排序可使用setget
這樣每次取出的第一個元素就是最小元素,由此再繼續生成新的ugly number.it
class Solution { public: int nthUglyNumber(int n) { set<long long> order; order.insert(1); int count = 0; long long curmin = 0; while(count < n) { curmin = *(order.begin()); order.erase(order.begin()); order.insert(curmin * 2); order.insert(curmin * 3); order.insert(curmin * 5); count ++; } return (int)curmin; } };