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

 ------------------------------------------------------------------------------------------------------------------------

返回target在有序数组中的位置。如果没有找到,就返回这个数应该放在的位置:

 代码如下:

int searchInsert(vector<int>& nums, int target) {
        if(nums.capacity() == 0) 
            return 0;
        if(target > nums[nums.capacity() - 1])     //如果要找的数比最后一个数还要大,它的位置应该在末尾
            return nums.capacity(); 
        for(int i = 0; i < nums.capacity(); i++){ 
            if(nums[i] >= target)                  //找到这个数,或者把它放在第一个比它大的数的位置
                return i;
        }
    }
原文地址:https://www.cnblogs.com/hozhangel/p/7846209.html