上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* @param {Array<number>} arr
* @param {number} startIndex
* @yields {number}
*/
var cycleGenerator = function* (arr, startIndex) {
};
/**
* 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
*/
javascript 解法, 执行用时: 56 ms, 内存消耗: 41.4 MB, 提交时间: 2023-10-15 14:40:50
/**
* @param {Array<number>} arr
* @param {number} startIndex
* @yields {number}
*/
var cycleGenerator = function* (arr, startIndex) {
var i = startIndex;
var x = yield arr[i];
while (true) {
i = (i + x + 10000 * arr.length) % arr.length;
x = yield arr[i];
}
};
/**
* 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
*/
typescript 解法, 执行用时: 68 ms, 内存消耗: 44 MB, 提交时间: 2023-10-15 14:40:25
function* cycleGenerator(arr: number[], startIndex: number): Generator<number, void, number> {
const arrLength = arr.length
while (true) {
let index = startIndex%arrLength
index = index<0 ? index+arrLength : index
const next = yield arr[index]
startIndex += next
}
};
function* cycleGenerator2(arr, startIndex) {
while (true) {
const jump = yield arr[startIndex]
startIndex = (startIndex + jump)
}
};
/**
* 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
*/