Ugly Number
Med 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 ...
Thoughts
参考自http://bookshadow.com/weblog/2015/08/19/leetcode-ugly-number-ii/
丑陋数序列可以拆分为下面3个子列表:
(1) 1×3, 3×3, 5×3, 7×3, 9×3, …
(2) 1×5, 3×5, 5×5, 7×5, 9×5, …
(3) 1×7, 3×7, 5×7, 7×7, 9×7, …
可以发现每一个子列表都是丑陋数本身(1, 3, 5, 7, 9, …) 乘以 3, 5, 7. 因此我们可以用三个指针,分别指向三行中下个可能的数,选取其中最小的加入。
Code
Analysis
光看出表还不够,还要注意里头有重复的元素。所以不能用if...else而是得三个if.
TC: O(k)
Last updated
Was this helpful?