There is an integer array nums sorted in ascending order (with distinct values).
Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].
Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.
You must write an algorithm with O(log n) runtime complexity.
Example 1
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
class Solution:
def search(self, nums: List[int], target: int) -> int:
arrayHash = {}
for i, v in enumerate(nums):
arrayHash[v] = i
return arrayHash[target] if target in arrayHash else -1
Time Complexity: O(N)
Space Complexity: O(N)
class Solution:
def search(self, nums: List[int], target: int) -> int:
lft = 0
rht = len(nums) - 1
while lft <= rht:
mid = (lft + rht) // 2
if nums[mid] == target:
return mid
### The right side is ordered
# 5, 6, 7, 0, 1, 2, 4
# 6, 7, 0, 1, 2, 4, 5
# 7, 0, 1, 2, 4, 5, 6
# 0, 1, 2, 4, 5, 6, 7
if nums[mid] < nums[rht]:
if target > nums[mid] and target <= nums[rht]:
lft = mid + 1
else:
rht = mid - 1
### The left side is ordered
# 4, 5, 6, 7, 0, 1, 2
# 1, 2, 4, 5, 6, 7, 0
# 2, 4, 5, 6, 7, 0, 1
else:
if target < nums[mid] and nums[lft] <= target:
rht = mid - 1
else:
lft = mid + 1
return -1
Time Complexity: O(logN)
Space Complexity: O(1)
class Solution:
def search(self, nums: List[int], target: int) -> int:
lft = 0
rht = len(nums) - 1
while lft <= rht:
mid = (lft + rht) // 2
if nums[mid] == target:
return mid
### The left side is ordered
# 4, 5, 6, 7, 0, 1, 2
# 1, 2, 4, 5, 6, 7, 0
# 2, 4, 5, 6, 7, 0, 1
if nums[mid] >= nums[lft]: # NOTE: for the edge case [3, 1], we have to use ">="
if target < nums[mid] and nums[lft] <= target:
rht = mid - 1
else:
lft = mid + 1
### The right side is ordered
# 5, 6, 7, 0, 1, 2, 4
# 6, 7, 0, 1, 2, 4, 5
# 7, 0, 1, 2, 4, 5, 6
# 0, 1, 2, 4, 5, 6, 7
else:
if nums[mid] <= target and target <= nums[rht]:
lft = mid + 1
else:
rht = mid - 1
return -1
Time Complexity: O(logN)
Space Complexity: O(1)
https://www.cnblogs.com/grandyang/p/4325648.html
TODO
Time Complexity: O()
Space Complexity: O()