首页 > 代码库 > 35. Search Insert Position

35. Search Insert Position

Given a sorted array 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 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

 

在一个排好序的数组查找某值,存在则返回对应的value,不存在则返回能插入到数组中的index,  其实就是找到第一个大于等于目标值的下标

 

 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 };

 

解释:

1、条件为target<=nums[mid],意思是target小于等于中间值,则往左半区域查找。如在 {1,2,2,2,4,8,10}查找2,第一步,low=0, high=6, 得mid=3, target <= a[3],往下标{1,2,2}中继续查找。

2、终止前一步为: low=high,得mid = low,此时如果target <= nums[mid],则high会改变,而low指向当前元素,即为满足要求的元素。如果target > nums[mid],则low会改变,而low指向mid下一个元素。

3、如果key大于数组最后一个元素,low最后变为nums.size(),即没有元素大于key,返回 nums.size()。

 

35. Search Insert Position