Skip to content

Commit 7504661

Browse files
authored
35. Search Insert Position
1 parent b3caaed commit 7504661

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

35. Search Insert Position

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/*
2+
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
3+
4+
You must write an algorithm with O(log n) runtime complexity.
5+
Binary search Algorithm
6+
*/
7+
int searchInsert(vector<int>& nums, int target) {
8+
int left = 0;
9+
int right = nums.size()-1; //length is used to extarct the amx size of array
10+
while(left <= right){
11+
int mid = left +(right - left)/2;
12+
if( nums[mid] == target){
13+
return mid;
14+
}
15+
else if(nums[mid] > target){
16+
right = mid -1;
17+
}
18+
else{
19+
left = mid+1;
20+
}
21+
}
22+
return left;
23+
}
24+
};

0 commit comments

Comments
 (0)