zoukankan      html  css  js  c++  java
  • 边工作边刷题:70天一遍leetcode: day 60-2

    Ugly Number I/II

    要点:I/II之间其实没多大关联,II和Super Ugly Number一样。基本思路就是逐个计算下一个ugly number直到n,用三个指针point2, point3, point5记录前一个2,3,5的位置。如果已经刚刚相乘取得新数,移动到改指针下一个ugly number的数上等待继续2,3,5。所以所有中间结果都要保留。
    错误点:注意每个数的指针不是移到最前端,而是下移一个数,所以要记录序列中的所有数

    I这题实际和Power of Three类似,就是怎么找整除。暴力解直接在loop里除每个因子,也可以用Power of Three的方法找最大整因子数%num看是不是==0

    class Solution(object):
        def nthUglyNumber(self, n):
            """
            :type n: int
            :rtype: int
            """
            point2, point3, point5 = 0,0,0
            dp = [0]*n
            dp[0]=1
            for i in xrange(1, n):
                dp[i] = min(dp[point2]*2, dp[point3]*3, dp[point5]*5)
                #print next
                if dp[i]/2==dp[point2]:
                    point2+=1
                if dp[i]/3==dp[point3]:
                    point3+=1
                if dp[i]/5==dp[point5]:
                    point5+=1
            
            return dp[n-1]
    
  • 相关阅读:
    [uoj173]鏖战表达式
    [cf1168E]Xor Permutations
    [cf578F]Mirror Box
    [cf1261F]Xor-Set
    [loj2506]tree
    [atARC068F]Solitaire
    [atARC066F]Contest with Drinks Hard
    [cf1270I]Xor on Figures
    [cf516D]Drazil and Morning Exercise
    无题
  • 原文地址:https://www.cnblogs.com/absolute/p/5690331.html
Copyright © 2011-2022 走看看