35 搜索插入位置 c++

leetcode35 搜索插入位置

c++实现

问题描述

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。

你可以假设数组中无重复元素。

算法思路

使用二分法进行查找。

假设插入位置为pos,则有nums[pos - 1] < target <= nums[pos]。

代码实现

#include
#include

using namespace std;

int searchInsert(vector<int>& nums , int target);

int main(){

    vector<int> nums(7);
    nums = {1,3,5,7,9,11,13};

    cout << searchInsert(nums, 10);
    cin.get();
    return 0;
}

int searchInsert(vector<int>& nums , int target){
    int n = nums.size();
    int left = 0, right = n - 1, pos = n;	// pos初始值设为n,因为当target为最大值时插入的位置为n。
    while(left <= right){
        int mid = ((right - left) >> 1 ) + left; // ">>"右移运算符表示对整数除以2向下取整
        if( target <= nums[mid]){
            pos = mid;
            right = mid -1;
        }else{
            left = mid + 1;
        }
    }

    return pos;
}

你可能感兴趣的:(算法问题)