在循環(huán)有序的序列中查找指定的值

/**
 * NOTE: 在一個(gè)循環(huán)有序的列表中查找指定的值。
 * 比如[6,7,8,1,2,3,4,5]就是一個(gè)循環(huán)有序數(shù)組。
 * 時(shí)間復(fù)雜度: O(logn), 空間: O(1)
 * 移動(dòng)中軸; 找到有序的序列, 然后從有序的序列中找到 target
 */

function find(list, target) {
  if (list.length === 0) {
    return -1
  }
  let start = 0
  let end = list.length - 1
  const res = []
  while (start <= end) {
    const mid = start + ((end - start) >> 1)
    if (list[mid] === target) {
      res.push(mid)
    }

    if (list[mid] >= list[start]) {
      // target 在 start - mid 之間
      if (target >= list[start] && target <= list[mid]) {
        end = mid - 1
      } else {
        // target 不在 start - mid 之間
        start = mid + 1
      }
    } else {
      if (target >= list[mid] && target <= list[end]) {
        start = mid + 1
      } else {
        end = mid - 1
      }
    }
  }
  return res
}

// test
const a = find([7, 7, 8, 9, 1, 2, 5, 6, 7, 9], 5);
console.log(a)
/*
  0: mid 4 = 1 , start: 0, 7; end 9, 9 =>
  1: mid 7, end: 9 start 5;
 */
// // const b = find([7, 7, 8, 9, 1, 2, 5, 6, 7, 7], 4);
// // const c = find([7, 7, 8, 9, 1, 2, 5, 6, 7, 7], 7);

// console.log(a, b, c);
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容