搜索插入位置力扣35

简介: 搜索插入位置力扣35
#include<iostream>
#include<vector>
using namespace std;
vector<int>a;
// 这道题只能选用左闭右开方法
int search(vector<int>nums,int targer)
{
    int left = 0;
    int right = nums.size()-1;
    while(left < right)
    {
        int middle = left + (right-left)/2;
        if(nums[middle]<targer)
        {
            left = middle ;
        }
        else if(nums[middle]>targer)
        {
            right = middle -1;
        }
        else
        {
            return middle;
        }
    }
    if(targer < nums[0])
    {
        return 0;
    }
    else if(targer>nums[nums.size()-1])
    {
        return nums.size();
    }
    else
    {
        return left+1;
    }
}
int main()
{
    int n;
    while(1)
    {
        cin >> n;
        a.push_back(n);
        if(cin.get()=='\n')
        {
            break;
        }
    }
    int tag;
    cin >> tag;
    int res;
    res = search(a,tag);
    cout << res;
    return 0;
}
目录
相关文章
|
2月前
|
算法
力扣240 搜索二维矩阵II
力扣240 搜索二维矩阵II
|
2天前
力扣每日一题 6/11 暴力搜索
力扣每日一题 6/11 暴力搜索
5 0
|
17天前
|
算法
【经典LeetCode算法题目专栏分类】【第6期】二分查找系列:x的平方根、有效完全平方数、搜索二位矩阵、寻找旋转排序数组最小值
【经典LeetCode算法题目专栏分类】【第6期】二分查找系列:x的平方根、有效完全平方数、搜索二位矩阵、寻找旋转排序数组最小值
|
17天前
|
算法
【经典LeetCode算法题目专栏分类】【第3期】回溯问题系列:单词搜索、N皇后问题、判断有效数独、解数独
【经典LeetCode算法题目专栏分类】【第3期】回溯问题系列:单词搜索、N皇后问题、判断有效数独、解数独
|
20天前
|
SQL 算法 数据可视化
LeetCode题目99:图解中叙遍历、Morris遍历实现恢复二叉树搜索树【python】
LeetCode题目99:图解中叙遍历、Morris遍历实现恢复二叉树搜索树【python】
|
20天前
|
存储 算法 数据可视化
python多种算法对比图解实现 验证二叉树搜索树【力扣98】
python多种算法对比图解实现 验证二叉树搜索树【力扣98】
|
20天前
|
存储 算法 数据挖掘
LeetCode 题目 81:搜索旋转排序数组 II
LeetCode 题目 81:搜索旋转排序数组 II
|
20天前
|
数据采集 机器学习/深度学习 算法
力扣79题:单词搜索
力扣79题:单词搜索
|
20天前
|
机器学习/深度学习 算法 数据挖掘
LeetCode题目74:搜索二维矩阵
LeetCode题目74:搜索二维矩阵
|
20天前
|
存储 算法 数据挖掘
高效搜索技巧:最小覆盖子串解法【力扣75题 python】
高效搜索技巧:最小覆盖子串解法【力扣75题 python】