这个解决方案找到旋转点(javascript)的时间复杂度是什么?

时间:2017-09-06 01:00:00

标签: javascript binary-search

问题是找到一个旋转点的索引,如下所示:

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);
  }
}

1 个答案:

答案 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']));