Loading content...
You are provided with a sorted array containing unique integers arranged in ascending order, along with a target value. Your task is to determine the position of the target value within the array.
If the target value exists in the array, return its index. If the target value does not exist, return the index where it should be inserted to maintain the sorted order of the array.
Your solution must achieve a time complexity of O(log n), where n is the length of the array. This constraint necessitates the use of an efficient search algorithm rather than a linear scan.
nums = [1,3,5,6]
target = 52The target value 5 is found at index 2 in the array, so we return 2.
nums = [1,3,5,6]
target = 21The target value 2 is not in the array. To maintain sorted order, it should be inserted at index 1 (between 1 and 3), so we return 1.
nums = [1,3,5,6]
target = 74The target value 7 is greater than all elements. It should be inserted at the end (index 4), so we return 4.
Constraints