题目描述:

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 Input: [1,3,5,6], 5
2 Output: 2

Example 2:

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

Example 3:

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

Example 4:

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

解题思路:

这题的思路是比较容易想到的,在数组中找到第一个大于或等于target的数。不过要注意target是数组中的数都大的情况。

代码:

1 int searchInsert(int* nums, int numsSize, int target) {
2     int i=0;
3     for(;i<numsSize;i++){
4         if(nums[i]>=target)
5             break;
6     }
7     return i;
8 }

 

posted on 2018-02-02 10:58  宵夜在哪  阅读(103)  评论(0编辑  收藏  举报