问题描述
Suppose an array sorted in ascending order 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.
Your algorithm’s runtime complexity must be in the order of O(log n).
例子
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
2019-06-09
字典
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dict = {nums[i]:i for i in range(len(nums))}
if dict.get(target) is not None:
return dict.get(target)
else:
return -1
结果分析
Runtime: 28 ms, faster than 71.73% of Python online submissions for Search in Rotated Sorted Array.
Memory Usage: 11.9 MB, less than 53.99% of Python online submissions for Search in Rotated Sorted Array.