简繁EN

LeetCodeNo. 125

【LeetCode with Python】 33. Search in Rotated Sorted Array

目錄

題目

原題頁面: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 7 might 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution:

def doSearch(self, A, left, right, target):
len_A = right - left + 1
if 0 == len_A:
return -1
elif 1 == len_A: ###
return left if target == A[left] else -1
if A[left] < A[right]:
while left <= right:
mid = (left + right) / 2
if A[mid] < target:
left = mid + 1
elif A[mid] > target:
right = mid - 1
else:
return mid
else:
mid = (left + right) / 2
left_result = self.doSearch(A, left, mid, target)
if -1 != left_result:
return left_result
else:
right_result = self.doSearch(A, mid + 1, right, target)
if -1 != right_result:
return right_result
return -1

# @param A, a list of integers
# @param target, an integer to be searched
# @return an integer
def search(self, A, target):
len_A = len(A)
return self.doSearch(A, 0, len(A) - 1, target)

本文地址:https://xnerv.wang/zh-tw/leetcode-search-in-rotated-sorted-array/