LeetCode No.264 Ugly Number II

来源:互联网 发布:网络潮州歌曲大全100首 编辑:程序博客网 时间:2024/06/05 08:11

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.

====================================================================================
题目链接:https://leetcode.com/problems/ugly-number-ii/
题目大意:求出第n个丑数。(丑数的因数只能是2,3,5并且第一个丑数为1)
思路:只需要保证每次迭代的过程中选取最小的丑数(或者说是质因数),可以理解为后面的数字是前面的数组针对2,3,5的乘积。 
附上代码:

class Solution {public:    int nthUglyNumber(int n) {        vector <int> ugly ( n , 0 ) ;        ugly[0] = 1 ;        int min2 = 2 , min3 = 3 , min5 = 5 ;        int index2 = 0 , index3 = 0 , index5 = 0 ;        for ( int i = 1 ; i < n ; i ++ )        {            int miner = minNum ( min2 , min3 , min5 ) ;            ugly[i] = miner ;            if ( miner == min2 )                min2 = 2 * ugly[++index2] ;            if ( miner == min3 )                min3 = 3 * ugly[++index3] ;            if ( miner == min5 )                min5 = 5 * ugly[++index5] ;        }        return ugly[n-1] ;    }private :    int minNum ( const int& a , const int& b , const int& c )    {        int miner = min ( a , b ) ;        return min ( miner , c ) ;    }};


0 0