35. Search Insert Position
Question:
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.
Example:
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 = 7
Output: 4
Input: nums = [1,3,5,6], target = 0
Output: 0
Input: nums = [1], target = 0
Output: 0
Source code
Version 1
Idea:
It is an intuitive method, use a loop to match each elements.
1 | class Solution { |
Version 2
Idea:
The solution is refered to Huahua's Tech Road.
It is an efficient approach to process large size of vector. m = l + (r - 1) / 2
is a key to divide into two parts. Then, get one of parts that consists target (Reduce computing time), repeats it until we find the accurate position.
1 | class Solution { |