【题目概要】
35. Search Insert Position
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
【思路分析】
- 存在返回index,不存在返回应该传入的index,找到第一个比它大的数,即为插入的index,超过遍历范围还是没有找到,应该在最后插入
【代码示例】
int searchInsert(int* nums, int numsSize, int target){
int index = 0;
for(index=0; index<numsSize; index++)
{
if(nums[index] >= target)
return index;
// if(nums[index] > target)
// return index;
}
return index;
}