leetcode-Medium-20期末-數(shù)組-Search in Rotated Sorted Array

題目

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).

假設(shè)一個(gè)升序的數(shù)組,在數(shù)組中任意一個(gè)位置旋轉(zhuǎn)后,在這個(gè)旋轉(zhuǎn)后的數(shù)組中找出給定目標(biāo)值target的位置,如果不存在返回-1

  • Example1
[0,1,2,4,5,6,7]--旋轉(zhuǎn)后--[4,5,6,7,0,1,2],target=0
所以返回0所在位置 4

  • Example2
[0,1,2,4,5,6,7]--旋轉(zhuǎn)后--[4,5,6,7,0,1,2],target=3
以返回0所在位置 3

  • 解法
let left = 0;
 let right = nums.length - 1
 while(left <= right){
   let mid = Math.floor( (left + right) /2 )
   if(nums[mid] === target) {
     return mid
  // 右邊數(shù)組,是有序的
   }else if(nums[mid] < nums[right] ){
 // 目標(biāo)值在右邊,繼續(xù)二分遍歷
      if(nums[mid] < target && target <= nums[right]) left = mid + 1
  // 目標(biāo)值在左邊,繼續(xù)二分遍歷
      else right = mid -1
   }else{// 這里說(shuō)明左邊是有序的
// 目標(biāo)值在左邊,繼續(xù)二分遍歷
      if(nums[mid] > target && nums[left] <= target) right = mid - 1
/ 目標(biāo)值不在左邊,那么肯定在右邊,繼續(xù)二分遍歷
      else left = mid + 1
   }
 }
// 遍歷完沒(méi)有目標(biāo)值返回-1
 return  -1

}
  • 題目分析
* 此題目關(guān)鍵在于,中間值如果小于數(shù)組最右邊的那個(gè)值,那么說(shuō)明右半部分?jǐn)?shù)組是有序的
nuns[mid] < nums[length - 1] // 右邊部分?jǐn)?shù)組有序
nuns[mid] > nums[length - 1] // 左邊部分?jǐn)?shù)組有序



?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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