題目
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
分析
給出一個以已排序的數(shù)組和一個目標值,如果找到相同的官研,返回索引值秽澳,否則返回可以插入的地方。
直接遍歷查找即可戏羽。其實也可以二分查找担神,可能速度會更快。
int searchInsert(int* nums, int numsSize, int target) {
int ans=0;
for(ans = 0;ans < numsSize ; ans++)
{
if(nums[ans] >= target)
break;
}
return ans;
}