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.
Input: nums = [1,3,5,6], target = 5
Output: 2
Input: nums = [1,3,5,6], target = 2
Output: 1
Input: nums = [1,3,5,6], target = 7Output: 4
nums contains distinct values sorted in ascending order.A straightforward approach to solve this problem is to go through the array and find the target or the position where it can be inserted in order. This is done by iterating over the array and checking each element against the target.
Since the array is sorted, we can use binary search to find the position for the target more efficiently. Binary search involves dividing the problem space in half during each iteration, making it much faster than a linear search.
left at the start and right at the end of the array.left is less than or equal to right:mid as the average of left and right (careful for overflows by using left + (right - left) / 2).nums[mid] is equal to the target, return mid.nums[mid] is less than the target, move left to mid + 1.nums[mid] is greater than the target, move right to mid - 1.left will be the position where the target should be inserted.