mirror of
https://github.com/Manoj-HV30/dsa-competitive-programming.git
synced 2026-05-16 19:35:22 +00:00
add codeforces solutions folder
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
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.
|
||||
*/
|
||||
Reference in New Issue
Block a user