Files

46 lines
1.3 KiB
C++

class Solution{
public:
int search(vector<int> nums, int target){
int start = 0, end = nums.size() - 1;
while(left<=right){
int mid = start + (end - start)/2;
if(nums[mid]==target) return mid;
if(nums[start]<=nums[mid]){
if(target>=nums[start] && target< nums[mid])
end = mid-1
else
start = mid+1;
}
else{
if(target>nums[mid] && target<= nums[end])
start = mid+1;
else
end = mid-1;
}
return -1;
}
};
//TC : o(logn), SC: o(1)
/*
Approach:
This is a modified binary search for a rotated sorted array.
The array was originally sorted in ascending order and then rotated once,
which means there is exactly one pivot point. Because of this, at any
given mid index, at least one half (left or right) must still be sorted.
At each step:
1) Find the middle index.
2) Determine which half is sorted.
3) Check if the target lies within the sorted half.
- If yes, move the search to that half.
- If no, move to the other half.
By always eliminating half of the array, we maintain
O(log n) time complexity without explicitly finding the pivot.
*/