丑数

题目

把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。

思路

所谓的一个数m是另一个数n的因子,是指n能被m整除,也就是n%m==0。根据丑数的定义,丑数只能被2、3和5整除。根据丑数的定义,丑数应该是另一个丑数乘以2、3或者5的结果(1除外)。因此我们可以创建一个数组,里面的数字是排好序的丑数,每一个丑数都是前面的丑数乘以2、3或者5得到的。

这个思路的关键问题在于怎样保证数组里面的丑数是排好序的。对乘以2而言,肯定存在某一个丑数T2,排在它之前的每一个丑数乘以2得到的结果都会小于已有最大的丑数,在它之后的每一个丑数乘以乘以2得到的结果都会太大。我们只需要记下这个丑数的位置,同时每次生成新的丑数的时候,去更新这个T2。对乘以3和5而言,也存在着同样的T3和T5。

 

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
	int GetUglyNumber_Solution(int index) {
		if (index < 7) {
			return index;
		}
		vector<int> res(index);
		for (int i = 0; i < 6; i++) {
			res[i] = i + 1;
		}
		// 1  2  3  4  5  6
		//   t5  t3 t2
		// 2 * 5 > 6     3*3 > 6  4 * 2>6 
		int t2 = 3, t3 = 2, t5 = 1;
		for (int i = 6; i < index; i++) {
			res[i] = min(res[t2] * 2, min(res[t3] * 3, res[t5] * 5));
			while (res[i] >= res[t2] * 2) {
				t2++;
			}
			while (res[i] >= res[t3] * 3) {
				t3++;
			}
			while (res[i] >= res[t5] * 5) {
				t5++;
			}
		}
		return res[index - 1];
	}
private:
	int min(int m, int n)
	{
		return m < n ? m : n;
	}
};

int main()
{
	Solution s;
	cout << s.GetUglyNumber_Solution(20) << endl;
	system("pause");
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值