標籤:
題目來源
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)
1 class Solution(object): 2 def search(self, nums, target): 3 """ 4 :type nums: List[int] 5 :type target: int 6 :rtype: bool 7 """ 8 size = len(nums) 9 first = 010 last = size - 111 while first <= last:12 mid = (last + first) / 213 print(first,mid, last)14 if nums[mid] == target:15 return True16 if nums[mid] == nums[first] == nums[last]:17 first += 1; last -= 118 elif nums[first] <= nums[mid]:19 if target < nums[mid] and target >= nums[first]:20 last = mid - 121 else:22 first = mid + 123 else:24 if target >= nums[mid] and target < nums[first]:25 first = mid + 126 else:27 last = mid - 128 29 30 31 return False32
[LeetCode]題解(python):081 - Search in Rotated Sorted Array II