[Array] LeetCode35. Search insertion position

35. Search insertion position

Given a sorted array and a target value, find the target value in the array and return its index. If the target value does not exist in the array, returns the position where it will be inserted in order.

Please use O(log n)an algorithm with a time complexity of .

Example 1:

输入: nums = [1,3,5,6], target = 5
输出: 2

Example 2:

输入: nums = [1,3,5,6], target = 2
输出: 1

Example 3:

输入: nums = [1,3,5,6], target = 7
输出: 4

hint:

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums is an array in ascending order without repeated elements
  • -104 <= target <= 104

the code

class Solution {
    
    
public:
    int searchInsert(vector<int>& nums, int target) {
    
    
        int left = 0;
        int right = nums.size() - 1;
        int middle = 0;
        while (left <= right) {
    
    
            middle = (left + right) / 2;
            if (nums[middle] < target) {
    
    
                left = middle + 1;
            }
            else if (nums[middle] > target) {
    
    
                right = middle - 1;
            }
            else {
    
    
                return middle; //找到
            }
        }

        //没找到,返回按顺序插入位置
        return left;
    }
};

Guess you like

Origin blog.csdn.net/Star_ID/article/details/131616747