Advertisement
Guest User

Untitled

a guest
May 25th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. class Solution:
  2. def search(self, nums, target):
  3. """
  4. :type nums: List[int]
  5. :type target: int
  6. :rtype: int
  7. """
  8. ## search in rotated array
  9. ## [0,1,2,4,5,6,7] => [4,5,6,7,0,1,2]
  10. ## So when rotated, there are two distinct non intersecting slices one after the other
  11. ## both are ascending. All the elements in the first slice are strictly greater than the ones in the
  12. ## second slice
  13. start, end = 0, len(nums) - 1
  14. while start <= end:
  15. mid = (start + end) // 2
  16. if target == nums[mid]:
  17. return mid
  18. ## cases for updatin binary search now
  19. ## target in the first slice
  20. if target > nums[mid] and target >= nums[0]:
  21. if nums[mid] >= nums[0]:
  22. ## target in the first slice. mid is also in the first slice
  23. start = mid + 1
  24. else:
  25. ## target in the first slice. mid is in the second slice
  26. end = mid - 1
  27. ## target in the second slice. Also mid in the second slice (because mid < nums[0])
  28. elif target > nums[mid] and target < nums[0]:
  29. start = mid + 1
  30. ## target in the first slice. Also mid in the first slice (because mid > nums[0])
  31. elif target < nums[mid] and target >= nums[0]:
  32. end = mid - 1
  33. ### target in the second slice
  34. else:
  35. ## mid is also in the first slice
  36. if nums[mid] >= nums[0]:
  37. start = mid + 1
  38. ## mid is in the second slice
  39. else:
  40. end = mid - 1
  41. return -1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement