class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int left = 0;
int right = nums.size()-1;
while(left<=right){
int mid = left + (right - left) / 2;
if (nums[mid] == target){
return mid;
}
else if (nums[mid] < target){
// search right array
left = mid + 1;
}
else {
// search left array
right = mid - 1;
}
} // break out of while loop
// now left > right
// nums[right] < target
// nums[left] > target
// we insert at position [left]
return left;
}
};
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.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.