Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def search(self, nums, target):
- """
- :type nums: List[int]
- :type target: int
- :rtype: int
- """
- ## search in rotated array
- ## [0,1,2,4,5,6,7] => [4,5,6,7,0,1,2]
- ## So when rotated, there are two distinct non intersecting slices one after the other
- ## both are ascending. All the elements in the first slice are strictly greater than the ones in the
- ## second slice
- start, end = 0, len(nums) - 1
- while start <= end:
- mid = (start + end) // 2
- if target == nums[mid]:
- return mid
- ## cases for updatin binary search now
- ## target in the first slice
- if target > nums[mid] and target >= nums[0]:
- if nums[mid] >= nums[0]:
- ## target in the first slice. mid is also in the first slice
- start = mid + 1
- else:
- ## target in the first slice. mid is in the second slice
- end = mid - 1
- ## target in the second slice. Also mid in the second slice (because mid < nums[0])
- elif target > nums[mid] and target < nums[0]:
- start = mid + 1
- ## target in the first slice. Also mid in the first slice (because mid > nums[0])
- elif target < nums[mid] and target >= nums[0]:
- end = mid - 1
- ### target in the second slice
- else:
- ## mid is also in the first slice
- if nums[mid] >= nums[0]:
- start = mid + 1
- ## mid is in the second slice
- else:
- end = mid - 1
- return -1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement