264、Ugly Number II
2015-10-22 16:09
337 查看
题目:
Write a program to find the
Ugly numbers are positive numbers whose prime factors only include
Note that
解题思路:
现有的丑陋数必须由一个较小的丑陋数乘以2,3或者5得到。
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, 12is the sequence of the first
10ugly numbers.
Note that
1is 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]; } };
相关文章推荐
- 一个含n个元素的整数数组至少存在一个重复数, 请编程实现,在O(n)时间内找出其中任意一个重复数。
- 网络编程 笔记(七) 进程间通信
- struts2文件上传与下载
- 协议[I2C]_I2C子系统之__I2C_first_dynamic_bus_num变量的相关分析
- Thinlphp 模版 foreach 嵌套在 另一个循环出现不能在次循环问题。
- PowerShell通过安全组创建计算机账号
- PowerShell通过安全组创建计算机账号
- 【VB.NET】视频总结
- win32程序启用控制台(控制台文件名:conout$,conin$,conerr$)
- linux脚本传输文件(本机到远程)
- STEP 7(s7-300)-----学习笔记
- 关于android-support-v7-appcompat.jar的使用的一些问题和解决方法
- 给定一个存放整数的数组,重新排列数组使得数组左边为奇数,右边为偶数。要求:空间复杂度O(1),时间复杂度为O(n)
- Python操作Redis之订阅与发布
- odoo8编辑视图中sheet边距过宽问题调整
- 控制dialog 的大小按屏幕大小的百分比设置
- android 获取string.xml中的value
- HDOJ 2001 计算两点间的距离
- 程序员书单_J2EE专题
- Xcode6 国际化(一)--应用名称国际化