Skip to content

Commit b74df1f

Browse files
committed
Binary Search: Search in Rotated Sorted Array in C++ #432
1 parent 7cd2609 commit b74df1f

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
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.
3+
You must write an algorithm with O(log n) runtime complexity.
4+
5+
Input: nums = [4,5,6,7,0,1,2], target = 0
6+
Output: 4
7+
8+
Input: nums = [4,5,6,7,0,1,2], target = 3
9+
Output: -1
10+
11+
Input: nums = [1], target = 0
12+
Output: -1
13+
14+
Constraints:
15+
> 1 <= nums.length <= 5000
16+
> -104 <= nums[i] <= 104
17+
> All values of nums are unique.
18+
> nums is an ascending array that is possibly rotated.
19+
> -104 <= target <= 104
20+
21+
APPROACH
22+
1. Find the index at which the array has been rotated with the help of Binary Search.
23+
2. Store the index of rotation as INDX and find the range where target might be found using the following comparision:
24+
RANGE = {INDX+1, HIGH} if TARGET < NUMS[LOW]
25+
RANGE = {LOW, INDX-1} if TARGET > NUMS{HIGH]
26+
3. Perform Binary Search for TARGET in the required range.
27+
4. If target is not found return -1.
28+
29+
TIME COMPLEXITY : O(NlogN) SPACE COMPLEXITY: O(1)
30+
*/
31+
class Solution {
32+
public:
33+
int search(vector<int>& nums, int target) {
34+
// Initialize Variable for later Usage
35+
int n=nums.size();
36+
int low=0;
37+
int high=n-1;
38+
39+
//Find the Rotation Point in the Rotated Array
40+
while(low<=high){
41+
int mid=(low+high)/2;
42+
if(mid==0 || mid==n-1){
43+
low=mid;
44+
break;
45+
}
46+
if(nums[mid-1]>nums[mid] && nums[mid+1]>nums[mid]){
47+
low=mid;
48+
break;
49+
}
50+
else if(nums[mid]>nums[low] && nums[mid]>nums[high]){
51+
low=mid+1;
52+
}
53+
else{
54+
high=mid-1;
55+
}
56+
}
57+
58+
// Re-initialize Variables Needed
59+
int indx=low;
60+
low=0, high=n-1;
61+
if(target==nums[indx]){
62+
return indx;
63+
}
64+
else if(target>nums[high]){
65+
high=indx-1;
66+
}
67+
else if(target<nums[low]){
68+
low=indx+1;
69+
}
70+
71+
// Binary Search for Target in range low-high
72+
while(low<=high){
73+
int mid=(low+high)/2;
74+
if(nums[mid]==target){
75+
return mid;
76+
}
77+
else if(target>nums[mid]){
78+
low=mid+1;
79+
}
80+
else{
81+
high=mid-1;
82+
}
83+
}
84+
85+
// If target not found return -1
86+
return -1;
87+
}
88+
};

0 commit comments

Comments
 (0)