[LeetCode]题解(python):033-Search in Rotated Sorted Array

时间:2023-03-09 08:35:40
[LeetCode]题解(python):033-Search in Rotated Sorted Array

题目来源


https://leetcode.com/problems/search-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 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.


题意分析


Input: a list with rotated sorted array with a unknown pivot

Output:index or -1

Conditions:在一个翻转数组中,找到target的位置,若不能找到则返回-1


题目思路


此题是关于二分查找的题目, 关键在于确定二分的位置,注意到数组仅是关于一个pivot位置的翻转,意味着这个pivot之前的值都是大于pivot之后的值的,所以在二分的时候利用好这个信息就好了

  1. 用first和last存储首尾位置,mid = (first + mid)// 2;
  2. 如果target等于nums[mid],返回target值;
  3. 如果nums[first] < nums[mid]:
  4. 如果nums[first] >= nums[mid]
  5. 对3,4两种条件,加上target与nums[mid]的值的比较,与target与nums[first]的比较,则可确定新的first与last的范围

AC代码(Python)


 class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
size = len(nums)
first = 0
last = size
while first < last: mid = (last + first) // 2
print(first,mid, last)
if nums[mid] == target:
return mid
elif nums[first] <= nums[mid]:
if target <= nums[mid] and target >= nums[first]:
last = mid
else:
first = mid + 1
else:
if target > nums[mid] and target < nums[first]:
first = mid + 1
else:
last = mid return -1