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.

Example 1:

1
Input: [1,3,5,6], 5
2
Output: 2

Example 2:

1
Input: [1,3,5,6], 2
2
Output: 1

Example 3:

1
Input: [1,3,5,6], 7
2
Output: 4

Example 4:

1
Input: [1,3,5,6], 0
2
Output: 0

1
class Solution {
2
public:
3
    int searchInsert(vector<int>& nums, int target) {
4
        int left = 0;
5
        int right = nums.size() - 1;
6
        int mid = (right - left) / 2 + left;
7
        while(left <= right) {
8
            mid = (right - left) / 2 + left;
9
            if (nums[mid] == target) {
10
                return mid;
11
            } else if (nums[mid] < target) {
12
                left = mid + 1;
13
            } else {
14
                right = mid - 1;
15
            }
16
        }
17
        if (nums[mid] < target) {
18
            return mid+1;
19
        } else {
20
            return mid;
21
        }
22
    }
23
};

Runtime: 8 ms