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. 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 class Solution {
 2 public:
 3     int searchInsert(vector<int>& nums, int target) {
 4         if (nums.size() == 0) {
 5             return 0;
 6         }
 7         int l = 0;
 8         int r = nums.size() - 1;
 9         while (l <= r) {
10             int mid = (l + r) / 2;
11             if (nums[mid] == target) {
12                 return mid;
13             } else if (nums[mid] < target) {
14                 l = mid + 1;
15             } else {
16                 r = mid - 1;
17             }
18         }
19         return l;
20     }
21 };
原文地址:https://www.cnblogs.com/sindy/p/6411922.html