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

时间:2022-02-19 08:08:58

题目来源


https://leetcode.com/problems/search-in-rotated-sorted-array-ii/

Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Write a function to determine if a given target is in the array.


题意分析


Input:

:type nums: List[int]
:type target: int

Output:

rtype: bool

Conditions:一个翻转的有序数组,数组元素可能重复,判断target是否在数组中


题目思路


关键就要区分边界,采用first表示下界,last表示上界,mid为中间点。如果mid为target,返回True;否则,判断mid,first,last是否相等,若相等则缩小搜索空间,之后判断target在哪个区间,判断条件为:1)target与nums[mid]的大小,target与nums[first]的大小。


AC代码(Python)

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