1
+ ##==================================
2
+ ## Leetcode
3
+ ## Student: Vandit Jyotindra Gajjar
4
+ ## Year: 2020
5
+ ## Problem: 33
6
+ ## Problem Name: Search in Rotated Sorted Array
7
+ ##===================================
8
+ #
9
+ #Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
10
+ #
11
+ #(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
12
+ #
13
+ #You are given a target value to search. If found in the array return its index, otherwise return -1.
14
+ #
15
+ #You may assume no duplicate exists in the array.
16
+ #
17
+ #Your algorithm's runtime complexity must be in the order of O(log n).
18
+ #
19
+ #Example 1:
20
+ #
21
+ #Input: nums = [4,5,6,7,0,1,2], target = 0
22
+ #Output: 4
23
+ #
24
+ #Example 2:
25
+ #
26
+ #Input: nums = [4,5,6,7,0,1,2], target = 3
27
+ #Output: -1
28
+ class Solution :
29
+ def search (self , nums , target ):
30
+ if not in nums : #Condition-check: If nums is empty
31
+ return - 1 #Return -1
32
+ low = 0 #Initialize low
33
+ high = len (nums ) - 1 #Initialize high
34
+ while low < high : #Loop
35
+ mid = (low + high ) // 2 #Initialize mid point
36
+ if target == nums [mid ]: #Condition-check: If target is mid
37
+ return mid #We return mid
38
+ if nums [low ] <= nums [mid ]: #Condition-check: If nums[low] <= nums[mid]
39
+ if nums [low ] <= target <= nums [mid ]: #Condition-check: If target is in the range
40
+ high = mid - 1 #Update high by mid - 1
41
+ else : #Condition-check: Else
42
+ low = mid + 1 #Update low by mid + 1
43
+ else :
44
+ if nums [mid ] <= target <= nums [high ] #Condition-check: If target is in the range
45
+ low = mid + 1 #Update low by mid + 1
46
+ else : #Condition-check: Else
47
+ high = mid - 1 #Update high by mid - 1
48
+ return - 1 #Otherwise we'll return -1
0 commit comments