264. Ugly Number II
Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
Example:
Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.Note:
1is typically treated as an ugly number.ndoes not exceed 1690.
My Solutions:
建立一个长度为n的数组nums。把2的倍数index2, 3的倍数index3,和5的倍数index5都设置为0。这些index代表由2/3/5乘以index之前,数字在nums中的index。必须要用nums里的数字和2/3/5相乘,这样产出的新数字只会被2/3/5整除。
nums的index = 0时数字是1,之后的每一位,找到2,3,5倍数后最小数。必须用num里已经有的数字乘以
0. nums=[1]
starts = [0,0,0]for numbers2,3,5, sonew_num = min(1*2,1*3,1*5) = 2, and nowstarts = [1,0,0],Numbers = [1,2].starts = [1,0,0], sonew_num = min(2*2,1*3,1*5) = 3, and nowstarts = [1,1,0],Numbers = [1,2,3].starts = [1,1,0], sonew_num = min(2*2,2*3,1*5) = 4, so nowstarts = [2,1,0],Numbers = [1,2,3,4].starts = [2,1,0], sonew_num = min(3*2,2*3,1*5) = 5, so nowstarts = [2,1,1],Numbers = [1,2,3,4,5].starts = [2,1,1], sonew_num = min(3*2,2*3,2*5) = 6, so let us be carefull in this case: we need to increase two numbers fromstart, because our new number6can be divided both by2and3, so nowstarts = [3,2,1],Numbers = [1,2,3,4,5,6].starts = [3,2,1], sonew_num = min(4*2,3*3,2*5) = 8, so nowstarts = [4,2,1],Numbers = [1,2,3,4,5,6,8]starts = [4,2,1], sonew_num = min(5*2,3*3,2*5) = 9, so nowstarts = [4,3,1],Numbers = [1,2,3,4,5,6,8,9].starts = [4,3,1], sonew_num = min(5*2,4*3,2*5) = 10, so we need to update two elements fromstartsand nowstarts = [5,3,2],Numbers = [1,2,3,4,5,6,8,9,10]starts = [5,3,2], sonew_num = min(6*2,4*3,3*5) = 12, we again need to update two elements fromstarts, and nowstarts = [6,4,2],Numbers = [1,2,3,4,5,6,8,9,10,12].starts = [6,4,2], sonew_num = min(8*2,5*3,3*5) = 15, we again need to update two elements fromstarts, and nowstarts = [6,5,3],Numbers = [1,2,3,4,5,6,8,9,10,12,15].
Last updated