Skip to content

Commit

Permalink
Create SearchInsertPosition.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
priyavelu7 authored Jun 10, 2020
1 parent 3c834bd commit 96ab0a6
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions Week 2/SearchInsertPosition.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
Given a sorted array 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.
You may assume no duplicates in the array.
Example 1:
Input: [1,3,5,6], 5
Output: 2
*/
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int left=0,right=nums.size()-1;
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]==target)
return mid;
else if(nums[mid]>target)
right=mid-1;
else left=mid+1;
}
return left;
}
};

0 comments on commit 96ab0a6

Please sign in to comment.