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:

1
2
Input: [1,3,5,6], 5
Output: 2

Example 2:

1
2
Input: [1,3,5,6], 2
Output: 1

Example 3:

1
2
Input: [1,3,5,6], 7
Output: 4

Example 4:

1
2
Input: [1,3,5,6], 0
Output: 0

分析

此题比较简单

分成两种情况

  1. 目标数在最后边
  2. 目标数在数组中某位的前边或者相等

    1. 目标数在最后边

    这种简单,直接返回数组的大小就好。

    2. 目标数在数组中某位的前边或者相等

    这种也相对简单,返回当前比较的数即可。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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;

}