您的位置:首页 > 其它

LeetCode算法问题13 —— Search Insert Position

2017-12-10 16:02 417 查看
问题描述:



要求给定一个已排序数组,以及一个目标值,如果数组中存在目标值,则返回第一次出现目标值的位置,否则返回应当插入数组中的哪个位置。

题目指示不会出现重复数在数组中,因此使用了二分查找法

int searchInsert(vector<int>& nums, int target) {
int low = 0, high = nums.size()-1;

// Invariant: the desired index is between [low, high+1]
while (low <= high) {
int mid = low + (high-low)/2;

if (nums[mid] < target)
low = mid+1;
else
high = mid-1;
}
return low;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: