-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch_in_sorted_array.cpp
More file actions
34 lines (29 loc) · 949 Bytes
/
search_in_sorted_array.cpp
File metadata and controls
34 lines (29 loc) · 949 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// 33. Search in Rotated Sorted Array: https://leetcode.com/problems/search-in-rotated-sorted-array/description/
// binary search, medium
/*
binary search impl with a twist of identifying sorted portion and then impl bs
*/
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0, mid;
int right = nums.size() - 1;
while(left <= right){
mid = left + (right - left) / 2;
if(target == nums[mid]) return mid;
if(nums[left] <= nums[mid]){
if(nums[left] <= target && target <= nums[mid])
right = mid - 1;
else left = mid + 1;
}
else if(nums[mid] <= nums[right]){
if(nums[mid] <= target && target <= nums[right])
left = mid + 1;
else right = mid - 1;
}
}
return -1;
}
};
// tc -> O(logn)
// sc -> O(1)