題目
原題頁面:https://leetcode.com/problems/search-in-rotated-sorted-array/
題目型別:Array, Binary Search
難度評價:Hard
類似題目:(M) Search in Rotated Sorted Array II, (M) Find Minimum in Rotated Sorted Array
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e.,
0 1 2 4 5 6 7might become4 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.
分析
二分查詢的一個變種。整個陣列由兩個有序的子序列構成,且左子序列中的每個元素都>,右子序列中的每個元素。
如果每次A[left]<=A[right],則說明當前段位於同一個有序子序列中。否則說明位於兩個不同的有序子序列中,此時以mid為界,將當前段拆成兩個子段,再遞迴這個過程。
題目中說明了陣列中沒有重複元素,因為有重複元素的情況下,上述演算法可能會有問題。例如,序列是[4 5 6 7 0 3 4],尋找的元素是3,則第一次時因為mid是7,則會進入左側段中查詢,則顯然是找不到3的。
程式碼
1 | class Solution: |
本文地址:https://xnerv.wang/zh-tw/leetcode-search-in-rotated-sorted-array/
