35. Search Insert Position, insertposition
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it wocould be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6]
, 5 → 2
[1,3,5,6]
, 2 → 1
[1,3,5,6]
, 7 → 4
[1,3,5,6]
, 0 → 0
Search for a value in an sorted array. If a value exists, the corresponding value is returned. If no value exists, the index that can be inserted into the array is returned,In fact, it is to find the first subscript that is greater than or equal to the target value..
1 class Solution { 2 public: 3 int searchInsert(vector<int>& nums, int target) { 4 int low = 0; 5 int high = nums.size()-1; 6 7 int mid = 0; 8 while(low <= high){ 9 mid = low + (high-low)/2;10 if(target <= nums[mid]){11 high = mid-1;12 }else{13 low = mid+1;14 }15 }16 return low;17 }18 };
Explanation:
1. The condition is target <= nums [mid], which means that if the target is smaller than or equal to the middle value, search for the target in the left half. For example, in {1, 2, 2, 4, 8, 10}, find 2. In the first step, low = 0, high = 6, obtain mid = 3, target <= a [3], search for the subscript {1, 2.
2. The first step to terminate is: low = high, and mid = low. At this time, if target <= nums [mid], high changes, and low points to the current element, it is the element that meets the requirements. If target> nums [mid], low changes, and low points to the next element of mid.
3. If the key is greater than the last element of the array, low changes to nums. size (). That is, if no element is greater than the key, nums. size () is returned ().