一. 题目描写叙述

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.

二. 题目分析

关于丑数的概念,可參考Ugly Number

从1開始的丑数为:1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … 该题的大意是,输入一个正整数n,返回第n个丑数。这要求比起Ugly Number一题是复杂了些。

其实,在观察这些丑数组合时,无非是分成例如以下三种组合(当中。第一个乘数为上一次计算得出的丑数,第一个丑数为1,第二个乘数为2、3、5中的一个数):

(以2为乘数)1×2, 2×2, 3×2, 4×2, 5×2, 6×2, 8×2, …
(以3为乘数)1×3, 2×3, 3×3, 4×3, 5×3, 6×3, 8×3, …
(以5为乘数)1×5, 2×5, 3×5, 4×5, 5×5, 6×5, 8×5, …

于是。开辟一个存放n个丑数的数组。在每次迭代时,从三种乘法组合中选取积最小的丑数并放入数组。最后数组的最后一个元素即是所求的丑数。

三. 演示样例代码

class Solution
{
public:
int nthUglyNumber(int n) {
int* uglyNum = new int[n]; // 用于存放前n个丑数
uglyNum[0] = 1; int factor2 = 2, factor3 = 3, factor5 = 5;
int index2, index3, index5;
index2 = index3 = index5 = 0; for(int i = 1; i < n; ++i)
{
// 取三组中的最小
int minNum = min(factor2, factor3, factor5);
uglyNum[i] = minNum; // 分三组计算
if(factor2 == minNum)
factor2 = 2 * uglyNum[++index2];
if(factor3 == minNum)
factor3 = 3 * uglyNum[++index3];
if(factor5 == minNum)
factor5 = 5 * uglyNum[++index5];
}
int temp = uglyNum[n-1];
delete [] uglyNum;
return temp;
} private:
// 求三个数的最小值
int min(int a, int b, int c) {
int minNum = a > b ? b : a;
return minNum > c ? c : minNum;
}
};

最新文章

  1. T1加权像(T1 weighted image,T1WI)
  2. iOS - 线程管理
  3. listed
  4. VS平台工具集版本
  5. bzoj 2761 [JLOI2011]不重复数字(哈希表)
  6. Eclipse创建新项目时无法输入项目名的解决方法
  7. Spring配置中&lt;context:annotation-config&gt; VS &lt;context:component-scan&gt;
  8. $_SERVER[&#39;HTTP_REFERER&#39;]的使用
  9. Scrapy Spider MiddleWare 设置
  10. java反射笔记
  11. OCaml相关
  12. Win平台阅读Kafka源码时候使用bat脚本时候报错以及解决方案
  13. MySQL processlist/kill
  14. 【delphi】delphi的TAdoQuery读取Excel数据
  15. spring jdbc连接数据库
  16. 1948 NOI 嘉年华
  17. SLG手游Java服务器的设计与开发——数据管理
  18. B/S 类项目改善的一些建议
  19. mysql把一字段拆分为多行
  20. AccessToken--&gt;Password Grant

热门文章

  1. 十一黄(xun)金(lian)周感想
  2. [HNOI2011][bzoj 2329] 括号修复 [splay+前缀和]
  3. [canvas入坑1]canvas 画布拖拽效果
  4. pdf生成(itextSharp)
  5. docker (centOS 7) 使用笔记6 - skydns
  6. vue 简易toDoList
  7. Nim积
  8. JQuery基础 学习的一些例子以及手册
  9. python编程(python开发的三种运行模式)【转】
  10. 《Linux命令行与shell脚本编程大全 第3版》Linux命令行---40