LeetCode-35. Search Insert Position
原文链接 https://www.aclihui.com/leetcode-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
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 4:
Input: [1,3,5,6], 0
Output: 0
分析
此题比较简单
分成两种情况
- 目标数在最后边
- 目标数在数组中某位的前边或者相等
1. 目标数在最后边
这种简单,直接返回数组的大小就好。
2. 目标数在数组中某位的前边或者相等
这种也相对简单,返回当前比较的数即可。
int searchInsert(int* nums, int numsSize, int target) {
int i=0;
if(target>nums[numsSize-1])
{
return numsSize;
}
else
{
for(i=0;i<numsSize;i++)
{
if(target<=nums[i])
{
return i;
}
}
}
return 0;
}