Leetcode 264. Ugly Number II[medium]

题目:
Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number.


先说自己的做法,比较挫。
假设已知前k个数字(a[1]-a[k]),则第k+1个必然是从k个数字中乘2,3,5得到的。
所以,可以在这k个数字中二分查找比a[k]/2,a[k]/3,a[k]/5大的第一个数字,从而生成a[k+1]。
时间复杂度O(nlogn)。
这里写图片描述

class Solution {
public:
    int nthUglyNumber(int n) {
        set<int> s;
        set<int>::iterator ita, itb, itc;
        s.insert(1);
        int mx = 1;
        while (s.size() < n) {
            ita = s.upper_bound(mx / 2);
            itb = s.upper_bound(mx / 3);
            itc = s.upper_bound(mx / 5);
            mx = min(*ita * 2, min(*itb * 3, *itc * 5));
            s.insert(mx);
        }
        return mx;
    }
};

然后发现我的排名很烂,去查看了discuss,这个题可以做到O(n)。
方法是不用二分查找,因为如果a[j]*2生成了a[k+1],则下一个通过乘2生成a[p](p>k+1)的必然是a[j+1].
利用这种思想省去二分查找的logn复杂度。
这里写图片描述

class Solution {
public:
    int nthUglyNumber(int n) {
        int ita, itb, itc;
        ita = itb = itc = 0;
        vector<int> v;
        v.push_back(1);
        while (v.size() < n) {
            int mx = min(v[ita] * 2, min(v[itb] * 3, v[itc] * 5));
            v.push_back(mx);
            if (mx == v[ita] * 2) ita++;
            if (mx == v[itb] * 3) itb++;
            if (mx == v[itc] * 5) itc++;
        }
        return v[n - 1];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值