繁体   English   中英

高效的数据结构和算法-自然序列

[英]Efficient Data structure and Algorithm - Natural Sequence

1 - 1
2 - 2,3
3 - 4,5,6
4 - 7,8,9,10

给定4到6之间的任何数字,我需要输出为3。

给定7到10之间的任何数字,我需要输出为4。

对于上述问题,我需要最快的解决方案来解决算法。

我能想到的是一种蛮力算法:

鉴于7:

n-square + n = 7*2 = 14
1 + 1 = 2  < 14
4 + 2 = 6  < 14
9 + 3 = 12 < 14
16+ 4 = 20 >=14 --> So 4 

有没有更好的方法来解决? 或我对算法本身的方法有缺陷吗?

算法的简要说明:

A,B,C

每次迭代后,每个元素都会增加一个。

A,A,B,B,C,C

给定3,将返回C。

给定4或5,将返回A。

给定6或7,将返回B。

给定8或9,将返回C。

给定10或11或12,将返回A。

给定13或14或15,将返回B。

数学问题的解决方案将如何帮助解决算法:

Total number of elements = 3

Given number = 13 (Output to be B)

Divide and Ceiling = Ceil (13/3) = 5 [So 13 falls under when every element has become * 3] (From Mathematical problem : If given number is 5, 3 is to be used)

Starting index of when every element has become * 3 [IS_EQUAL_TO = ] 3 * 3(summation of previous iteration => 1 + 2) + 1 = 10

To Find the index = Ceil(13-10+1/3 (this 3,comes from the mathematical problem) ) = Ceil (4/3) = 2nd index = B

给定行数N,三角形的大小为N(N + 1)/ 2。 本质上,您正在尝试找到最小整数N,以使N(N + 1)/ 2> = M,并给出M。 如果您具有计算平方根的功能,则可以在固定时间内求解此方程。

N(N + 1)/ 2> = M,将两边乘以2,
N²+ N> = 2M,完成平方,取平方根,等等
N> =平方(2M + 1/4)-1/2

因此答案是N = ceil(sqrt(2*M + .25) - .5)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM