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.

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

 

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

 

posted @ 2016-05-16 21:32  米开朗菠萝  阅读(143)  评论(0编辑  收藏  举报