[LeetCode 解题报告]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

Example:

Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note:  

  1. 1 is typically treated as an ugly number.
  2. n does not exceed 1690.
class Solution {
public:
    int nthUglyNumber(int n) {
        vector<int> res(1, 1);
        int i2 = 0, i3 = 0, i5 = 0;
        
        while (res.size() < n) {
            int num2 = res[i2]*2, num3 = res[i3]*3, num5 = res[i5]*5;
            int mn = min(num2, min(num3, num5));
            
            if (mn == num2)
                i2 ++;
            if (mn == num3)
                i3 ++;
            if (mn == num5)
                i5 ++;
            res.push_back(mn);
        }
        return res.back();
    }
};
发布了480 篇原创文章 · 获赞 40 · 访问量 46万+

猜你喜欢

转载自blog.csdn.net/caicaiatnbu/article/details/104235293