代码拉取完成,页面将自动刷新
同步操作将从 doocs/leetcode 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
给定你一个 循环 数组 arr
和一个整数 startIndex
,返回一个生成器对象 gen
,它从 arr
中生成值。第一次调用 gen.next()
时,它应该生成 arr[startIndex]
。每次调用 gen.next()
时,都会传入一个整数参数 jump
(例如:gen.next(-3)
)。
jump
是正数,则索引应该增加该值,但如果当前索引是最后一个索引,则应跳转到第一个索引。jump
是负数,则索引应减去该值的绝对值,但如果当前索引是第一个索引,则应跳转到最后一个索引。
示例 1:
输入:arr = [1,2,3,4,5], steps = [1,2,6], startIndex = 0 输出:[1,2,4,5] 解释: const gen = cycleGenerator(arr, startIndex); gen.next().value; // 1, index = startIndex = 0 gen.next(1).value; // 2, index = 1, 0 -> 1 gen.next(2).value; // 4, index = 3, 1 -> 2 -> 3 gen.next(6).value; // 5, index = 4, 3 -> 4 -> 0 -> 1 -> 2 -> 3 -> 4
示例 2:
输入:arr = [10,11,12,13,14,15], steps = [1,4,0,-1,-3], startIndex = 1 输出:[11,12,10,10,15,12] 解释: const gen = cycleGenerator(arr, startIndex); gen.next().value; // 11, index = 1 gen.next(1).value; // 12, index = 2 gen.next(4).value; // 10, index = 0 gen.next(0).value; // 10, index = 0 gen.next(-1).value; // 15, index = 5 gen.next(-3).value; // 12, index = 2
示例 3:
输入:arr = [2,4,6,7,8,10], steps = [-4,5,-3,10], startIndex = 3 输出:[7,10,8,4,10] 解释: const gen = cycleGenerator(arr, startIndex); gen.next().value // 7, index = 3 gen.next(-4).value // 10, index = 5 gen.next(5).value // 8, index = 4 gen.next(-3).value // 4, index = 1 gen.next(10).value // 10, index = 5
提示:
1 <= arr.length <= 104
1 <= steps.length <= 100
-104 <= steps[i], arr[i] <= 104
0 <= startIndex < arr.length
function* cycleGenerator(arr: number[], startIndex: number): Generator<number, void, number> {
const n = arr.length;
while (true) {
const jump = yield arr[startIndex];
startIndex = (((startIndex + jump) % n) + n) % n;
}
}
/**
* const gen = cycleGenerator([1,2,3,4,5], 0);
* gen.next().value // 1
* gen.next(1).value // 2
* gen.next(2).value // 4
* gen.next(6).value // 5
*/
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。