leetcode 【 Search in Rotated Sorted Array II 】python 实现
题目:
与上一道题几乎相同;不同之处在于array中允许有重复元素;但题目要求也简单了,只要返回true or false
http://www.cnblogs.com/xbf9xbf/p/4254590.html
代码:oj测试通过 Runtime: 73 ms
1 class Solution: 2 # @param A a list of integers 3 # @param target an integer 4 # @return a boolean 5 def search(self, A, target): 6 A=list(set(A)) 7 # none case & zero case 8 if A is None or len(A)==0 : 9 return False 10 # binary search 11 start = 0 12 end = len(A)-1 13 while start<=end : 14 # one element left case 15 if start == end : 16 if A[start]==target : 17 return True 18 else: 19 return False 20 # two elements left case 21 if start+1 == end : 22 if A[start]==target : 23 return True 24 elif A[end]==target : 25 return True 26 else: 27 return False 28 # equal or more than three elements case 29 mid = (start+end)/2 30 if A[mid]==target : 31 return True 32 elif A[mid]>target: 33 if A[start]>A[mid] and A[end]<A[mid]: 34 start = mid+1 35 elif A[start]<A[mid] and A[end]<A[mid]: 36 if A[end]>=target: 37 start = mid+1 38 else: 39 end = mid-1 40 elif A[start]>A[mid] and A[end]>A[mid]: 41 end = mid-1 42 else: 43 end = mid-1 44 else: 45 if A[start]>A[mid] and A[end]<A[mid]: 46 end = mid-1 47 elif A[start]<A[mid] and A[end]<A[mid]: 48 start = mid+1 49 elif A[start]>A[mid] and A[end]>A[mid]: 50 if A[end]>=target : 51 start = mid+1 52 else: 53 end = mid-1 54 else: 55 start = mid+1 56 return False
思路:
用了一个trick Python数组去重的办法A=list(set(A))
这样A数组中就没有重复的元素了,可以直接用之前一题的代码。
这样的trick应该不是题目的本意,这道二分查找题目比较经典,应该吃透。