C++程序查找第n个丑数
假设我们有一个数字n;我们需要找到第n个丑数。众所周知,丑数是指其质因数只有2、3和5的数字。因此,如果我们想找到第10个丑数,输出将是12,因为前几个丑数是1、2、3、4、5、6、8、9、10、12等等。
为了解决这个问题,我们将遵循以下步骤
- 定义一个大小为(n + 1)的数组v
- 如果n等于1,则
- 返回1
- two := 2,three := 3,five := 5
- twoIdx := 2,threeIdx := 2,fiveIdx := 2
- 从i := 2开始,当i <= n时,更新(i增加1),执行以下操作:
- curr := two、three和five中的最小值
- v[i] := curr
- 如果curr等于two,则
- two := v[twoIdx] * 2;
- (twoIdx增加1)
- 如果curr等于three,则
- three := v[threeIdx] * 3
- (threeIdx增加1)
- 如果curr等于five,则
- five := v[fiveIdx] * 5
- (fiveIdx增加1)
- 返回v[n]
让我们看看下面的实现,以便更好地理解
示例
#include
using namespace std;
class Solution {
public:
int nthUglyNumber(int n) {
vector v(n + 1);
if(n == 1){
return 1;
}
int two = 2, three = 3, five = 5;
int twoIdx = 2;
int threeIdx = 2;
int fiveIdx = 2;
for(int i = 2; i <= n; i++){
int curr = min({two, three, five});
v[i] = curr;
if(curr == two){
two = v[twoIdx] * 2;;
twoIdx++;
}
if(curr == three){
three = v[threeIdx] * 3;
threeIdx++;
}
if(curr == five){
five = v[fiveIdx] * 5;
fiveIdx++;
}
}
return v[n];
}
};
main(){
Solution ob;
cout << (ob.nthUglyNumber(15));
}输入
15
输出
24
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP