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

题目来源


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 = 0
10         last = size - 1
11         while first <= last:
12             mid = (last + first) / 2
13             print(first,mid, last)
14             if nums[mid] == target:
15                 return True
16             if nums[mid] == nums[first] == nums[last]:
17                 first += 1; last -= 1
18             elif nums[first] <= nums[mid]:
19                 if target < nums[mid] and target >= nums[first]:
20                     last = mid - 1
21                 else:
22                     first = mid + 1
23             else:
24                 if target >= nums[mid] and target < nums[first]:
25                     first = mid + 1
26                 else:
27                     last = mid - 1
28 
29 
30 
31         return False
32         

 

posted @ 2016-04-08 10:33  loadofleaf  Views(327)  Comments(0Edit  收藏  举报