素因子都在集合{2, 3, 5, 7}内的整数称为ugly number 求第n大的丑数
分析
1.初始:把1放入优先队列中
2.每次从优先队列中取出一个元素k,把2k, 3k,5k, 7k放入优先队列中
3.从2开始算,取出的第n个元素就是第n大的丑数
4.每取出一个数,插入4个数,因此任何堆里的元素是O(n)的,时间复杂度为O(nlogn)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List f = new List() { 2, 3, 5, 7 };
List q = new List() { 1 };
int i = 0;
int n = 30;
while (i++ < n)
{
int k = q.Min();
q.RemoveAll(x => x == k);
q.AddRange(f.Select(x => x * k));
Console.WriteLine(k);
}
}
}
}
1
2
3
4
5
6
7
8
9
10
12
14
15
16
18
20
21
24
25
27
28
30
32
35
36
40
42
45
48
49
请按任意键继续. . .
这是按照你描述写的,另外C语言版的各种实现,Google下ugly number有很多,值得注意的是,很多算法将2 3 5视作因子,不包括7,你需要略微修改。