LeetCode

来源:互联网 发布:淘宝店铺内部人员解封 编辑:程序博客网 时间:2024/06/08 19:08

263. Ugly Number

Write a program to check whether a given number is an ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.

Note that 1 is typically treated as an ugly number.


判断一个数是不是丑数,由于只包含素因子2,3,5,那就除以这三个素因子到不能初为止,若剩下1,就是丑数。时间复杂度O(logn),空间复杂度0

class Solution {public:    bool isUgly(int num) {        if (num == 0) return false;        while (num % 2 == 0) num /= 2;        while (num % 3 == 0) num /= 3;        while (num % 5 == 0) num /= 5;        if (num == 1) return true;        return false;    }};




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. 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, and n does not exceed 1690.


用丑数去推去丑数,如果一个数是丑数,那么他*2,*3,*5一定是丑数。时间复杂度O(n),空间复杂度O(n)

class Solution {public:    int nthUglyNumber(int n) {        vector<int> ans(n, 0);        ans[0] = 1;        int k2 = 0, k3 = 0, k5 = 0;        for (int i = 1; i < n; ++i) {            ans[i] = min(ans[k2] * 2, min(ans[k3] * 3, ans[k5] * 5));            if (ans[i] == ans[k2] * 2) k2++;            if (ans[i] == ans[k3] * 3) k3++;            if (ans[i] == ans[k5] * 5) k5++;        }        return ans[n-1];    }};




313. Super Ugly Number

Write a program to find the nth super ugly number.

Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k. For example, [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] is the sequence of the first 12 super ugly numbers given primes = [2, 7, 13, 19] of size 4.

Note:
(1) 1 is a super ugly number for any given primes.
(2) The given numbers in primes are in ascending order.
(3) 0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000.
(4) The nth super ugly number is guaranteed to fit in a 32-bit signed integer.


上一题的扩展版,把丑数的限制放开,给出素数表来求。但是基本思想还是一样的,用丑数去推出丑数,取每次计算出的最小的丑数。时间复杂度O(n*primes.size()),空间复杂度O(n+primes.size())

class Solution {public:    int nthSuperUglyNumber(int n, vector<int>& primes) {        vector<int> ans(n, 0);        ans[0] = 1;        vector<int> k(primes.size(), 0);        for (int i = 1; i < n; ++i) {            int cur = ans[k[0]] * primes[0];            for (int j = 0; j < primes.size(); ++j) {                cur = min(cur, ans[k[j]]*primes[j]);            }            ans[i] = cur;            for (int j = 0; j < primes.size(); ++j) {                if (cur == ans[k[j]]*primes[j]) k[j]++;            }        }        return ans[n-1];    }};

原创粉丝点击