删除数组中的每个奇数索引,直到数组中的元素数变为1

Emp*_*mp1 0 algorithm logic

您有一个大小为n = 10的数组;

arr [] = {1,2,3,4,5,6,7,8,9,10}

操作1:-删除每个奇数索引:-1,3,5,7,9现在arr [] = {2,4,6,8,10}

重复操作1除非在这种情况下数组的大小变为1,否则答案为:-8

是否有任何公式可以直接解决。

Shi*_*vam 5

1)假设索引从1开始。

然后,

数学解释:

 Index of the element that will stay up to the end = 2^(?log2 n?) 
 where ?n? is: floor of log of n base 2.
 And, n is the size of the array.
Run Code Online (Sandbox Code Playgroud)

最后元素的索引将始终为最大2 ^ k <= n,其中k为正整数。

例如:如果n = 20,则组成最后一个元素的索引为16。

即2 ^ 4

如果n = 40,答案将是32 ==> 2 ^ 5


2)如果索引从零开始,则第0个元素将保留到结束。