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

來源:互聯網
上載者:User

標籤:

題目來源

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.