标签:style blog http color io os ar for sp
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7
might become 4 5 6 7 0 1 2
).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
There two solutions:
Solution 1: How to hand the specific case involved point a,b and c?
Solution 2: How to hand the specific case involved point a, nd d?
Solution 1:
class Solution: # @param A, a list of integers # @param target, an integer to be searched # @return an integer def search(self, A, target): return self.helper(A, target, 0, len(A)-1) def helper(self, A, target, low, high): if low > high: return -1 mid = (low + high) / 2 if target == A[mid]: return mid elif A[low] <= target < A[mid] or ( A[mid] <= A[high] and (target < A[mid] or target > A[high]) ): return self.helper(A, target,low, mid-1) else: return self.helper(A, target,mid+1, high)
Solution 2:
class Solution: # @param A, a list of integers # @param target, an integer to be searched # @return an integer def search(self, A, target): low,high = 0,len(A)-1 while low <= high: mid = (low+high+1)/2 if A[mid]==target: return mid if A[low] <= A[mid]: if A[low] <= target < A[mid]: high=mid-1 else: low=mid+1 else: if A[mid] < target <= A[high]: low=mid+1 else: high=mid-1 return -1
[leetcode] Search in Rotated Sorted Array @ Python [Figure][自配插图说明]
标签:style blog http color io os ar for sp
原文地址:http://www.cnblogs.com/asrman/p/4044704.html