题解 | #丑数#

丑数

https://www.nowcoder.com/practice/6aa9e04fc3794f68acf8778237ba065b?tpId=265&tqId=39247&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3FjudgeStatus%3D3%26page%3D1%26pageSize%3D50%26search%3D%26tpId%3D13%26type%3D265&difficulty=undefined&judgeStatus=3&tags=&title=

class Solution {
public:
    int GetUglyNumber_Solution(int index) {
      if (index == 0) {
        return 0;
      }
      
      //  存放丑数
      std::vector<int> num;
      int count = 1;
      num.push_back(1);
      //  所有丑数都是由1乘上 2 3 5 得到的
      //  这里取最小的丑数乘上各自质因子中的最小数
      int i = 0, j = 0, k = 0;
      
      while (count < index) {
        int tmp = std::min(num[i] * 2, std::min(num[j] * 3, num[k] * 5));
        num.push_back(tmp);
        
        //  乘上相应的数之后,该位不能再乘上同一个质因子
        if (num[count] == num[i] * 2) {
          ++i;
        }
        if (num[count] == num[j] * 3) {
          ++j;
        }
        if (num[count] == num[k] * 5) {
          ++k;
        }
        
        ++count;
      }
      
      return num[count - 1];
    }
};
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务