leetcode 二分查找

代码:

cpp 复制代码
class Solution {
public:
    int search(vector<int>& nums, int target) {
        int n = nums.size();
        int left = 0;
        int right = n-1;
        int res = -1;
        while(left <= right){
            int mid = (left+right)/2;
            if(nums[mid] == target){
                res = mid;
                break;
            }
            else if(nums[mid] > target){
                right = mid -1;
            }
            else{
                left = mid + 1;
            }
        }
        return res;
    }
};

代码:

cpp 复制代码
class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int n = nums.size();
        int left = 0;
        int right = n-1;
        int res = 0;
        int mid = 0;
        while(left <= right){
            mid = (left + right)/2;
            if(nums[mid] == target){
                res = mid;
                break;
            }else if(nums[mid] > target){
                right = mid -1;
            }else{
                left = mid +1;
            }
        }
        if(left >right)
            res = left;
        return res;
    }
};
相关推荐
feifeigo12310 分钟前
基于马尔可夫随机场模型的SAR图像变化检测源码实现
算法
fengfuyao98535 分钟前
基于STM32的4轴步进电机加减速控制工程源码(梯形加减速算法)
网络·stm32·算法
无敌昊哥战神2 小时前
深入理解 C 语言:巧妙利用“0地址”手写 offsetof 宏与内存对齐机制
c语言·数据结构·算法
小白菜又菜2 小时前
Leetcode 2075. Decode the Slanted Ciphertext
算法·leetcode·职场和发展
Proxy_ZZ02 小时前
用Matlab绘制BER曲线对比SPA与Min-Sum性能
人工智能·算法·机器学习
黎阳之光2 小时前
黎阳之光:以视频孪生领跑全球,赋能数字孪生水利智能监测新征程
大数据·人工智能·算法·安全·数字孪生
小李子呢02112 小时前
前端八股6---v-model双向绑定
前端·javascript·算法
2301_822703203 小时前
Flutter 框架跨平台鸿蒙开发 - 创意声音合成器应用
算法·flutter·华为·harmonyos·鸿蒙
cmpxr_4 小时前
【C】数组名、函数名的特殊
c语言·算法
KAU的云实验台4 小时前
【算法精解】AIR期刊算法IAGWO:引入速度概念与逆多元二次权重,可应对高维/工程问题(附Matlab源码)
开发语言·算法·matlab