Search Insert Position
Given a sorted array of distinct integers and a target, return the index if the target is found. If not, return the index where it would be inserted to keep the array sorted. You must run in O(log n) time.
Open official problem prompt ↗Locate a target in a sorted array, or the exact slot it would occupy, using logarithmic search.
Like slipping a new book onto an alphabetized shelf: you binary-search to the first title that is not before yours, and that gap is where the book goes.
- Input
- nums = [1, 3, 5, 6], target = 5
- Output
- 2
- Why
- The value 5 is already present at index 2.
1 <= nums.length <= 10^4-10^4 <= nums[i] <= 10^4nums contains distinct values sorted in ascending order-10^4 <= target <= 10^4