面试题34:丑数
来源:互联网 发布:在淘宝不给退货怎么办 编辑:程序博客网 时间:2024/05/21 02:19
问题描述: 我们把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第1500个丑数。
错误解法:
#include<iostream>using namespace std;#include <math.h>//错误的做法,考虑不周。但想到用数学方法解题也是一种思路。int GetUglyNumber(int n){ if(0==n || 1==n){ return 1; } int i2=0; int i3=0; int i5=0; i2=i3=i5=(n-1)/3; if((n-1)%3==1){ i2++; }else if((n-1)%3==2){ i2++; i3++; } return pow(2,i2)*pow(3,i3)*pow(5,i5);//凭什么是按顺序相乘呢,还可以是乘以4。}
方法一:遍历
/************************************************************************* > Created Time: Mon 09 May 2016 02:11:23 PM PKT ************************************************************************/#include<iostream>using namespace std;//方法一:遍历。即使一个数组不是丑数,也要对它求余数,除法等操作,效率不足。bool IsUglyNumber(int n){ while(n%2==0){ n/=2; } while(n%3==0){ n/=3; } while(n%5==0){ n/=5; } return n==1?true:false;}int GetUglyNumber1(int n){ if(n<=1){ return 1; } int cnt=1; int number=1; while(cnt<n){ number++; if(IsUglyNumber(number)){ cnt++; } } return number;}//测试void test(){ cout<<GetUglyNumber1(1500)<<endl;}
方法二:创建数组保存已经找到的丑数,用空间换时间。效率高
/************************************************************************* > Created Time: Mon 09 May 2016 02:11:23 PM PKT ************************************************************************/#include<iostream>using namespace std;#include <vector>int Min(int a,int b,int c){ int min=(a<b?a:b); return min<c?min:c;}//方法二int GetUglyNumberTwo(int n){ vector<int> vec(n); vec[0]=1; int t2=0; int t3=0; int t5=0; int next=1; while(next<n){ vec[next]=Min(vec[t2]*2,vec[t3]*3,vec[t5]*5); while(vec[t2]*2<=vec[next]){ t2++; } while(vec[t3]*3<=vec[next]){ t3++; } while(vec[t5]*5<=vec[next]){ t5++; } next++; } return vec[n-1];}//测试void test(){ cout<<GetUglyNumberTwo(1500)<<endl;}
运行结果为:第1500个丑数是859963392
0 0
- 面试题34:丑数
- 面试题34:丑数
- 面试题34:丑数
- 面试题34 丑数
- 面试题34:丑数
- 面试题34:丑数
- 面试题34:丑数
- 【面试题34】丑数
- 面试题34:丑数
- 面试题34:丑数
- 面试题34:丑数
- 面试题34:丑数
- 面试题34:丑数
- 面试题 34: 丑数
- [剑指offer][面试题34]丑数
- [剑指offer]面试题34:丑数
- 剑指Offer:面试题34 丑数
- 剑指offer 面试题34 丑数
- Composer安装说明
- 线程之join()
- Qt之自定义搜索框
- 关于串的kmp匹配问题
- jquery 加载等待效果
- 面试题34:丑数
- OpenCV 轮廓的凸性
- 局域网内任何一台pc上windows下eclipse远程连接hbase数据库
- 最美好地祝福我们自己
- Python Built-in Funcitons
- Android用GridView画带背景色和点击事件的简单表格
- 在myeclipse中奖java项目打包成jar文件
- HUST Sum of Consecutive Prime Numbers
- Xmppframework could not build module dnssd或者libxml