给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;
while (left <= right) {
int middle = left + ((right - left)/2);
if ( nums[middle] > target){
right = middle -1;
}
else if (nums[middle] < target){
left = middle +1;
}
else {
return middle;
}
}
return left;
}
};
标签:target,middle,int,nums,35,插入,搜索,目标值,left
From: https://www.cnblogs.com/onelemon/p/16786092.html