1,题目要求
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.
对一个已经进行排序的数组中寻找目标值,如果找到了就返回对应的index,否则就返回target应该在位置的index。
2,题目思路
直接进行遍历查找就可以实现,或者利用二分查找的思想。
3,程序源码
直接法:(8ms)
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
for(int i=0;i<nums.size();i++)
{
if(nums[i] >= target )
return i;
}
return nums.size();
}
};
二分查找法:(7ms)
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int low = 0, high = nums.size()-1;
while(low<=high)
{
int mid = low + (high - low)/2;
if(target == nums[mid])
return mid;
else if(target>nums[mid])
low = mid+1;
else
high = mid-1;
}
return low;
}
};
当while循环完成时,说明没有找到对应的数字,此时low > high,即low = high+1。因为数字树位于[low, hight+1]中的,也即位于[low,low]之中,因此返回low,即为target的最后的位置。

本文介绍了一种在已排序数组中查找目标值的方法,并提供了两种实现方式:直接遍历法和二分查找法。直接遍历法易于理解,而二分查找法则更高效。
458

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



