[Lintcode]4. Ugly Number II/[Leetcode]264. Ugly Number II
阿新 • • 發佈:2019-02-18
app 超時 algo [1] algorithm com output amp hat
4. Ugly Number II / 264. Ugly Number II
- 本題難度: Medium
Topic: Data Structure
Description
Ugly number is a number that only have factors 2, 3 and 5.
Design an algorithm to find the nth ugly number. The first 10 ugly numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12...
Example
Example 1:
Input: 9
Output: 10
Example 2:
Input: 1
Output: 1
Challenge
O(n log n) or O(n) time.
Notice
Note that 1 is typically treated as an ugly number.
我的代碼 超時。因為每個數都要判斷一次
def nthUglyNumber(self, n: ‘int‘) -> ‘int‘: cur = 1 while(n-1): cur += 1 if self.isUgly(cur): n -= 1 return cur def isUgly(self, n): ugly = [2,3,5] for i in ugly: while(n % i == 0): n //= i return n == 1
別人的代碼
class Solution: def nthUglyNumber(self, n: ‘int‘) -> ‘int‘: res = [1] i2 = i3 = i5 = 0 while(n>1): u2, u3, u5 = 2*res[i2], 3*res[i3], 5*res[i5] uCurr = min(u2,u3,u5) if uCurr == u2: i2 += 1 if uCurr == u3: i3 += 1 if uCurr == u5: i5 += 1 res.append(uCurr) n -= 1 return res[-1]
思路
非常巧妙的思路。
所有ugly number都是由2,3,5組成的,所以他們肯定都是由2,3,5乘以之前的數得到,i2,i3,i5記錄的分別是當前還未被乘2,3,5過的數字,接下來的ugly number肯定在其中,因為比它們更小的都已經在res中了
- 時間復雜度 O(n)
[Lintcode]4. Ugly Number II/[Leetcode]264. Ugly Number II