35. Search Insert Position

来源:互联网 发布:网络机柜走线视频教程 编辑:程序博客网 时间:2024/06/14 08:57

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

 考虑有四种情况,如各个实例表明:

当被搜索的数值在数组中时,直接返回下标;

当被搜索的数值不在数组中但是在其中两个数之间则返回较大范围值的下标;

当被搜索的值<vec[0],返回0;

当被搜素的值>vec[vec.size()-1],返回vec.size();

class Solution 

{
public:
    int searchInsert(vector<int>& nums, int target) 

    {

      int len=nums.size();

      for(int i=0;i<len;i++)

         {

           if(target==nums[i])

           return i;

           if(nums[i]<target&&nums[i+1])

           return i+1;

         }

       if(target>nums[len])
        return len;
        if(target<nums[0])
        return 0;

    }

};

原创粉丝点击