Ugly Number II

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.



class Solution {
public:
    int nthUglyNumber(int n) {
        vec.reserve(n);
        vec.push_back(1);
        int i2 = 0;
        int i3 = 0;
        int i5 = 0;
        for(int i =1; i < n; ++i)
        {
            int val2 = vec[i2] * 2;
            int val3 = vec[i3] * 3;
            int val5 = vec[i5] * 5;
            if(val2 < val3)
            {
                if(val2 < val5)
                {
                    ++i2;
                    vec.push_back(val2);
                }
                else
                {
                    ++i5;
                    vec.push_back(val5);
                    i2+=(val2 == val5);
                }
            }
            else if(val2 > val3)
            {
                if(val3 val5)
				{
					++i5;
					vec.push_back(val5);
				}
				else
				{
				    ++i2;
				    ++i3;
				    vec.push_back(val2);
				    i5+=(val2 == val5);
				}
            }
        }
        return vec[n-1];
    }
    void addVal(int val)
    {
        vec.push_back(val);
    }
    vector vec;
};


你可能感兴趣的:(LeetCode)