[Lintcode]4. Ugly Number II/[Leetcode]264. Ugly Number II

本文探讨了如何高效地找到第N个丑数,即仅包含2、3、5为质因数的正整数。介绍了两种算法实现,一种是直接判断每个数是否为丑数,但效率较低;另一种是使用动态规划思想,通过维护三个指针来快速生成丑数序列,最终实现O(n)的时间复杂度。

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值