问题:
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.
Example 1:
Input: [1,3,5,6], 5 Output: 2
Example 2:
Input: [1,3,5,6], 2 Output: 1
Example 3:
Input: [1,3,5,6], 7 Output: 4
Example 1:
Input: [1,3,5,6], 0 Output: 0
简化一下题意,这道题首先给我们一个目标值,让我们找出它在一个有序数组中应插入的位置(如果数组中有相同值的话就插在它的前面)。可以很容易就想到二分查找。需要注意的是,找到最后一个位置的时候,判断目标值应该插在该位置还是位置的右方。若目标值为a,最后一个位置的值为b,当a>b时,插在位置右方;否则插在该位置。
代码如下:
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int start = 0 , end = nums.size() - 1;
int mid = ( start + end ) / 2;
//二分查找
while( start < end ){
if( nums[mid] > target ){
end = mid - 1;
}else if( nums[mid] < target) {
start = mid + 1;
}else{
return mid;
}
mid = ( start + end ) / 2;
}
//这里要注意判断返回值与mid的关系
if( nums[mid] < target ){
return mid + 1;
}
return mid;
}
};
有序数组插入位置

本文介绍了一种使用二分查找算法解决有序数组中插入位置问题的方法。对于给定的目标值,在有序数组中找到合适的插入位置,使得数组保持有序状态。文章通过具体的示例详细解释了算法的实现过程。
1561

被折叠的 条评论
为什么被折叠?



