Leetcode 264. Ugly Number II[medium]

来源:互联网 发布:外网无法访问8080端口 编辑:程序博客网 时间:2024/05/22 00:17

题目:
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
原创粉丝点击