smj007

Untitled

Jun 22nd, 2022
380
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | None | 0 0
  1. class Solution:
  2.     def nthUglyNumber(self, n: int) -> int:
  3.        
  4.         # ugly numbers are represented by
  5.         # ugly = (2**x)(3**y)(5**y)
  6.         prev_mult_of_2_index = 0
  7.         prev_mult_of_3_index = 0
  8.         prev_mult_of_5_index = 0
  9.         uglys = []
  10.         uglys.append(1)
  11.        
  12.        
  13.         for i in range(n-1):
  14.            
  15.             # next multiple of 2 = 2*(previous multiple of 2)
  16.             # next multiple of 3 and next multiple of 5 likewise
  17.             # So the idea is that we are trying to record which one was
  18.             # the last multiple of 2, 3 and 5
  19.             next_multiple_of_2 = uglys[prev_mult_of_2_index]*2
  20.             next_multiple_of_3 = uglys[prev_mult_of_3_index]*3
  21.             next_multiple_of_5 = uglys[prev_mult_of_5_index]*5
  22.            
  23.             min_ugly = min(next_multiple_of_2, next_multiple_of_3, next_multiple_of_5)
  24.             uglys.append(min_ugly)
  25.            
  26.             if min_ugly == next_multiple_of_2:
  27.                 prev_mult_of_2_index += 1
  28.                
  29.             if min_ugly == next_multiple_of_3:
  30.                 prev_mult_of_3_index += 1
  31.                
  32.             if min_ugly == next_multiple_of_5:
  33.                 prev_mult_of_5_index += 1
  34.                
  35.         return uglys[n-1]
Advertisement
Add Comment
Please, Sign In to add comment