我想要一个返回子阵列的函数,它需要一个位置&否。我想要的元素。我认为可能有一些算法来找到支点或&从我可以得到的子数组,但我完全忘了它。基于位置获取阵列中的N个元素
Example: a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
I want 6 elements
if position = 0, then I want [1, 2, 3, 4, 5, 6]
if position = 1, then [1, 2, 3, 4, 5, 6]
if position = 2, then [1, 2, 3, 4, 5, 6]
if position = 3, then [1, 2, 3, 4, 5, 6]
if position = 4, then [2, 3, 4, 5, 6, 7]
if position = 5, then [3, 4, 5, 6, 7, 8]
if position = 6, then [4, 5, 6, 7, 8, 9]
if position = 7, then [5, 6, 7, 8, 9, 10]
if position = 8, then [5, 6, 7, 8, 9, 10]
if position = 9, then [5, 6, 7, 8, 9, 10]
simply get the middle of N elements based on the position I pass.
我可以写我自己的loop
其中将包含多个if-else
条件把它完成。但我觉得可能有一些简单的方法来做到这一点。
我没有包括我的不完整的代码片断,因为我强烈地感觉到必须有一些算法来做到这一点。
如何使用的位置?当你指定位置为4时,为什么要跳过第一个元素? – fafl
这就像,如果我的位置是阵列的中心位置,让我中间阵列有N个元素。这是否有意义 – Garfield
好吧,我错过了,我得到一个开始索引和最小长度。我会相应地更新我的摘录。 :) –