Search Insert Position

Description:

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

Code:

 1     int searchInsert(vector<int>& nums, int target) {
 2         int left = 0, right = nums.size()-1;
 3         
 4         while (left <= right)
 5         {
 6             int mid = (left + right)/2 ;
 7             if (target == nums[mid])
 8                 return mid;
 9             else if (target < nums[mid])
10             {
11                 right = mid-1;
12             }
13             else
14             {
15                 left = mid+1;
16             }
17         }
18         return left;
19     }
原文地址:https://www.cnblogs.com/happygirl-zjj/p/4577485.html