剑指offer——51丑数

题目描述

把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
 
  
 1 //使用遍历判断的方法
 2 class Solution01 {
 3 public:
 4     int GetUglyNumber_Solution(int index) {
 5         if (index < 1)return 0;
 6         int cnt = 0;
 7         for (int i = 1; cnt < index; ++i)
 8         {
 9             if (isChouShu(i))
10                 cnt++;
11             if (cnt == index)
12                 return i;
13         }
14     }
15     bool isChouShu(int num)
16     {
17         while (num % 2 == 0)
18             num /= 2;
19         while (num % 3 == 0)
20             num /= 3;
21         while (num % 5 == 0)
22             num /= 5;
23         return num == 1;
24     }
25 };
26 
27 
28 //使用保存数据法
29 class Solution02 {
30 public:
31     int GetUglyNumber_Solution(int index) {
32         if (index < 1)return 0;
33         vector<int>v(index, 0);
34         v[0] = 1;
35         int p2, p3, p5, k = 1;
36         p2 = p3 = p5 = 0;
37         while (k < index)
38         {
39             v[k++] = min(min(v[p2] * 2, v[p3] * 3), v[p5] * 5);
40             while (v[p2] * 2 <= v[k - 1])p2++;
41             while (v[p3] * 3 <= v[k - 1])p3++;
42             while (v[p5] * 5 <= v[k - 1])p5++;
43         }
44         return v[index - 1];
45     }
46 };

 

posted @ 2019-10-18 21:02  自由之翼Az  阅读(113)  评论(0编辑  收藏  举报