您的位置:首页 > 其它

264、Ugly Number II

2015-10-22 16:09 337 查看
题目:

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];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: