forked from Hrudhay-H/Cpp_Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetcode_35.cpp
More file actions
26 lines (26 loc) · 821 Bytes
/
Copy pathLeetcode_35.cpp
File metadata and controls
26 lines (26 loc) · 821 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
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int low = 0, high = nums.size() - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (nums[mid] == target)
return mid; // Return immediately if target is found
else if (nums[mid] < target)
low = mid + 1; // Search in the right half
else
high = mid - 1; // Search in the left half
}
return low; // The correct insertion index
}
};
int main() {
Solution obj;
vector<int> nums = {1,3,5,6};
int target = 5;
cout << obj.searchInsert(nums, target) << endl;
return 0;
}