Search Insert Position
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.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [1,3,5,6], target = 5
Output: 2
Example 2:
Input: nums = [1,3,5,6], target = 2
Output: 1
First Try
Given the O(log n) runtime complexity, we should use binary search. First think about normal binary search,
1 | function BinarySearchFirst(arr, target) { |
we need to make adjustment on last return, when highIndex < = lowIndex, it means we can’t find a number equal to target, then we need to insert the target into the array, position will either be lowIndex or lowIndex+1.
The final submission is below:
1 | /** |
Runtime: 72 ms, faster than 80.09% of JavaScript online submissions for Search Insert Position.
Memory Usage: 40 MB, less than 12.53% of JavaScript online submissions for Search Insert Position.
If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !