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
题目大意:给出一个排好序的数组和一个待插入元素,问该元素应该插入到数组到什么位置。
解题思路:复习考试,做一道水题吧。类似于插入排序,扫一遍数组就可以了。
代码如下:
int searchInsert(int* nums, int numsSize, int target) {
int ans,flag = 0;
for(int i = 0;i < numsSize;i++){
if(target <= nums[i]){
ans = i;
flag = 1;
break;
}
}
return flag == 1 ? ans : numsSize;
}