Due to Python's powerful built-in functions, we have a slick solution:
try:
return nums.index(target)
except:
return -1
Run Time is 60 ms.
The normal way is to use binary search. Because there can be at most 1 turning point, the update of bounds is not complex.
Solution:
# T:O(lgn) S:O(1) 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) while low < high: mid = low + (high - low) / 2 if A[mid] == target: return mid if A[low] <= A[mid]: if A[low] <= target and target < A[mid]: high = mid else: low = mid + 1 else: if A[mid] < target and target <= A[high - 1]: low = mid + 1 else: high = mid return -1Run Time: 52 ms
No comments:
Post a Comment