查找第K次数最少为前pression(2 ^ X)*(3 ^ Y)*(5 ^ Z) [英] Find the Kth least number for expression (2^x)*(3^y)*(5^z)

查看:201
本文介绍了查找第K次数最少为前pression(2 ^ X)*(3 ^ Y)*(5 ^ Z)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在EX pression

In the expression

2 X * 3 * 5 以Z

2x * 3y * 5z

X 以Z 可以非负整数值(> = 0)。

The x, y and z can take non negative integer value (>=0).

所以,函数将生成一个序列号 1,2,3,4,5,6,8,9,10,12,15,16的......

So the function would generate a series of number 1,2,3,4,5,6,8,9,10,12,15,16....

  • 在我有一个蛮力解决方案。
  • 我将基本上遍历在循环中以1开始,在每个迭代我会发现如果当前数目的因素是只从该组2,3或5

我想有是一个优雅的算法。

What I would like to have is an elegant algorithm.

这是一个面试问题。

推荐答案

这可以通过使用优先级队列,您存储三胞胎解决的(X,Y,Z)的排序键的 2 X 3 5 以Z 的。

This can be solved using a priority queue, where you store triplets (x, y, z) sorted by the key 2x3y5z.

  1. 启动仅与三重态的(0,0,0)的队列中的

删除三重的(X,Y,Z)的从队列中最小的关键。

Remove the triplet (x, y, z) with the smallest key from the queue.

将三个三元的(X + 1,Y,Z)(X,Y + 1,Z)(X, Y,Z + 1)的的队列中。请确保你不插入任何已经在那里了。

Insert the three triplets (x+1, y, z), (x, y+1, z) and (x, y, z+1) in the queue. Make sure you don't insert anything that was already there.

重复步骤2,直到您已删除的 K 的三胞胎。最后一个被移除的是你的答案。

Repeat from step 2 until you've removed k triplets. The last one removed is your answer.

在实际上,这成为本向无环图的有序遍历。 (这里显示的前三个级别,实际的图形当然是无限的)。

In effect, this becomes a sorted traversal of this directed acyclic graph. (First three levels shown here, the actual graph is of course infinite).

这篇关于查找第K次数最少为前pression(2 ^ X)*(3 ^ Y)*(5 ^ Z)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆