简体   繁体   English

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

[英]Efficient Data structure and Algorithm - Natural Sequence

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

Given any number from 4 to 6 ,I need the output as 3. 给定4到6之间的任何数字,我需要输出为3。

Given any number from 7 to 10 ,I need the output as 4. 给定7到10之间的任何数字,我需要输出为4。

I need the fastest solution for the above problem to solve an algorithm. 对于上述问题,我需要最快的解决方案来解决算法。

What I could think of is a brute force algorithm : 我能想到的是一种蛮力算法:

Given 7: 鉴于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 

Is there any better approach to arrive at the solution ? 有没有更好的方法来解决? OR My approach to the algorithm itself is flawed ? 或我对算法本身的方法有缺陷吗?

Brief explanation of the algo : 算法的简要说明:

A,B,C

After every iteration every element becomes increased by one. 每次迭代后,每个元素都会增加一个。

A,A,B,B,C,C

Given 3, C will be returned. 给定3,将返回C。

Given 4 or 5, A will be returned. 给定4或5,将返回A。

Given 6 or 7, B will be returned. 给定6或7,将返回B。

Given 8 or 9, C will be returned. 给定8或9,将返回C。

Given 10 or 11 or 12, A will be returned. 给定10或11或12,将返回A。

Given 13 or 14 or 15, B will be returned. 给定13或14或15,将返回B。

How the solution to the mathematical problem will help solve the algo : 数学问题的解决方案将如何帮助解决算法:

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

Given number of rows N, the size of the triangle is N(N+1)/2. 给定行数N,三角形的大小为N(N + 1)/ 2。 You are essentially trying to find the least integer N such that N(N+1)/2 >= M, with M given. 本质上,您正在尝试找到最小整数N,以使N(N + 1)/ 2> = M,并给出M。 If you have a function to compute square roots, you can solve this equation in constant time. 如果您具有计算平方根的功能,则可以在固定时间内求解此方程。

N(N+1)/2 >= M, multiply both sides with 2, N(N + 1)/ 2> = M,将两边乘以2,
N²+N >= 2M, complete the square, take the square root, blablabla N²+ N> = 2M,完成平方,取平方根,等等
N >= sqrt(2M+1/4)-1/2 N> =平方(2M + 1/4)-1/2

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

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

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