简繁EN

LeetCodeNo. 125

[LeetCode with Python] 33. Search in Rotated Sorted Array

Contents

Problem

Problem page: https://leetcode.com/problems/search-in-rotated-sorted-array/
Topics: Array, Binary Search
Difficulty: Hard
Similar problems: (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.


Analysis

This is a variation on binary search. The array consists of two sorted subsequences. Every element in the left subsequence is greater than every element in the right one.
At each step, if A[left]<=A[right], the current segment lies within one sorted subsequence. Otherwise, it spans both sorted subsequences. Split the segment in two at mid and repeat the process recursively.
The problem says the array has no duplicates, because the algorithm can run into trouble with duplicates. For example, suppose the array is [4 5 6 7 0 3 4] and we're looking for 3. On the first step, the value at mid is 7, so we search the left segment. We won't find 3 there.


Code

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)

Article link: https://xnerv.wang/en/leetcode-search-in-rotated-sorted-array/