问题是找到一个旋转点的索引,如下所示:
var letters = ['c', 'd', 'e', 'a', 'b']; // -> 3 because it's the index of 'a'
我试图在O(log n)时间内完成它,使用切片使它成为O(n log n)吗?
这是我的解决方案:
var findRotationPointLogN = function(array, addedLength) {
var midpointIndex = Math.floor(array.length / 2);
var right = array.slice(midpointIndex);
var left = array.slice(0, midpointIndex);
if (array[midpointIndex] < array[midpointIndex - 1]) {
if (addedLength) {
return midpointIndex + addedLength;
} else {
return midpointIndex;
}
} else if (array[midpointIndex] > array[0]) {
if (addedLength) {
return findRotationPointLogN(right, addedLength + left.length);
} else {
return findRotationPointLogN(right, left.length);
}
} else if (array[midpointIndex] < array[0]) {
return findRotationPointLogN(left, 0);
}
}
答案 0 :(得分:0)
这不是字母小于前一个字母的点吗?
const r = l => l.reduceRight((p, c, i, a) => a[i-1] && a[i].charCodeAt(0) < a[i-1].charCodeAt(0) ? i : p, 0);
console.log(r(['c', 'd', 'e', 'a', 'b']));