首页 > 代码库 > 【LeetCode】Math

【LeetCode】Math

[263] Ugly Number [Easy]

一个数的质因子只有2,3,5就叫丑数,写个函数判断丑数。

技术分享
 1 //Author: Wanying
 2 //注意 0 和 1 的corner case, 你居然还没一次AC==
 3 //想好了再写,不然等着挂吧==!!!!!
 4 class Solution {
 5 public:
 6     bool isUgly(int num) {
 7         if (num == 0 || num == 1) {
 8             return num;
 9         }
10         while(num % 2 == 0) {
11             num = num / 2 ;
12         }
13         while(num % 3 == 0) {
14             num = num / 3;
15         }
16         while(num % 5 == 0) {
17             num = num / 5;
18         }
19         return num == 1;
20     }
21 };
View Code

 

[264] Ugly Number II [Medium]

第一个丑数是1,返回第n个丑数是多少。

思路:dp, 第u个丑数一定是 min(vec[idx2]*2, vec[idx3]*3, vec[idx5] *5) || 所以,要存idx2,idx3,idx5, 而且vec里面不能有重复的丑数.

技术分享
 1 //Author: Wanying
 2 //DP: idx2, idx3, idx5
 3 
 4 class Solution {
 5 public:
 6     int nthUglyNumber(int n) {
 7         vector<int> vec(1,1);
 8         int idx2 = 0, idx3 = 0, idx5 = 0;
 9         for(size_t i = 2; i <= n; ++i) {
10             int v2 = vec[idx2] * 2, v3 = vec[idx3] * 3, v5 = vec[idx5] * 5;
11             int ith = min(v2, min(v3, v5));
12             if (ith == v2) {
13                 idx2++;
14             } 
15             if (ith == v3) {
16                 idx3++;
17             }
18             if (ith == v5) {
19                 idx5++;
20             }
21             vec.push_back(ith);
22         }
23         return vec[n-1];
24     }
25 };
View Code

 

[313] Super Ugly Number [Medium]

跟Ugly Number II类似, 变化在于质因子不是[2,3,5]了,变成了透传进来的数组。 所以思路就从用3个idx变成了用一个数组的idx,其他一样,注意bug-free.

技术分享
 1 //Author: Wanying
 2 class Solution {
 3 public:
 4     int nthSuperUglyNumber(int n, vector<int>& primes) {
 5         vector<int> idx(primes.size(), 0);
 6         vector<int> ans(1, 1);
 7         for (size_t i = 2; i <= n; ++i) {
 8             int ith = INT_MAX;
 9             for (int j = 0; j < primes.size(); ++j) {
10                 int tmp = ans[idx[j]] * primes[j];
11                 ith = min(tmp, ith);
12             }
13             for (int j = 0; j < primes.size(); ++j) {
14                 int tmp = ans[idx[j]] * primes[j];
15                 if (ith == tmp) {
16                     idx[j] ++;
17                 }
18             }
19             ans.push_back(ith);
20         }
21         return ans[n-1];
22     }
23 };
View Code

 

【LeetCode】Math