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.
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]; }};
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- sybase 主键自动增长
- 2017十大网络黑客攻击事件丨阿里云河南
- 合天网安实验室:CTF-MISC练习
- Windows系统版本判断
- QT 中使用 Windows API----SendMessage() 进行窗体间消息传递
- LeetCode
- ScrollView 和 RecyclerView 嵌套问题
- springmvc常用注解标签详解
- VS2013+Cmake便于g2o遇到问题:error MSB3073: 命令“setlocal D:\tools\cmake-3.6.0-rc3-win32-x86\bin\cmake.exe -D
- AI的过去和未来
- 正则的几道练习
- 用户管理,组管理,权限管理
- mysql--触发器使用
- 面向对象程序编程,自己之前不知道的小知识,学习笔记