C++ 中的丑数 II


假设我们要找到第 n 个丑数,那么我们必须定义一种可以找到它的方法。我们知道丑数是指那些质因子仅为 2、3 和 5 的数字。因此,如果我们要找到第 10 个丑数,它将是 12,因为前几个丑数是 1、2、3、4、5、6、8、9、10、12

为了解决这个问题,我们将遵循以下步骤:-

  • 制作一个大小为 n + 1 的数组 v

  • 如果 n = 1,则返回 1

  • two := 2,three = 3 和 five = 5,towIndex := 2,threeIndex := 2 和 fiveIndex := 2

  • 对于 2 到 n 范围内的 i

    • curr := two、three 和 five 的最小值

    • v[i] := curr

    • 如果 curr = two,则 two := v[twoIndex] * 2,将 twoIndex 增加 1

    • 如果 curr = three,则 three := v[threeIndex] * 3,将 threeIndex 增加 1

    • 如果 curr = five,则 five := v[fiveIndex] * 3,将 fiveIndex 增加 1

  • 返回 v[n]

示例 (C++)

让我们看看以下实现以更好地理解 -

 实时演示

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int nthUglyNumber(int n) {
      vector <int> v(n + 1);
      if(n == 1){
         return 1;
      }
      int two = 2, three = 3, five = 5;
      int twoIdx = 2;
      int threeIdx = 2;
      int fiveIdx = 2;
      for(int i = 2; i <= n; i++){
         int curr = min({two, three, five});
         v[i] = curr;
         if(curr == two){
            two = v[twoIdx] * 2;;
            twoIdx++;
         }
         if(curr == three){
            three = v[threeIdx] * 3;
            threeIdx++;
         }
         if(curr == five){
            five = v[fiveIdx] * 5;
            fiveIdx++;
         }
      }
      return v[n];
   }
};
main(){
   Solution ob;
   cout << (ob.nthUglyNumber(10));
}

输入

10

输出

12

更新于: 02-May-2020

229 次浏览

开启您的 职业生涯

完成课程,赢取认证

开始
广告
© . All rights reserved.