264、Ugly Number II

来源:互联网 发布:企业网络商学院 编辑:程序博客网 时间:2024/05/20 07:33

题目:

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.

解题思路:

现有的丑陋数必须由一个较小的丑陋数乘以2,3或者5得到。

class Solution(object):    def nthUglyNumber(self, n):        """        :type n: int        :rtype: int        """        uglyNum = [1]        i2,i3,i5 = 0,0,0                while len(uglyNum)<n:            num = min(uglyNum[i2]*2,uglyNum[i3]*3,uglyNum[i5]*5)            if num == uglyNum[i2]*2:   #防止重复值出现                i2 += 1            if num == uglyNum[i3]*3:   #防止重复值出现                i3 += 1            if num == uglyNum[i5]*5:   #防止重复值出现                i5 += 1            uglyNum.append(num)        return uglyNum[-1]


class Solution {public:    int nthUglyNumber(int n) {        vector<int> uglyNum(1,1);        int index2=0,index3=0,index5=0;        while(uglyNum.size()<n)        {            uglyNum.push_back(min(uglyNum[index2]*2,min(uglyNum[index3]*3,uglyNum[index5]*5)));            if(uglyNum[index2]*2==uglyNum.back())index2++;            if(uglyNum[index3]*3==uglyNum.back())index3++;            if(uglyNum[index5]*5==uglyNum.back())index5++;        }        return uglyNum[n-1];    }};





0 0