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;
}

本文介绍了一个简单的算法问题:在一个已排序的数组中找到特定值的插入位置。此问题类似于插入排序的过程,通过遍历数组即可解决。文章给出了具体的C语言实现代码。
132

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



