当前位置:网站首页>leetcode704. 二分查找(查找某个元素,简单,不同写法)

leetcode704. 二分查找(查找某个元素,简单,不同写法)

2022-07-06 06:55:00 重you小垃

在这里插入图片描述
在这里插入图片描述
要点:始终维护的区间和初始时的位置是一样的即可。

1:左开右开

class Solution {
    
public:
    int search(vector<int>& nums, int target) {
    
     
        int l = -1, r = nums.size();
        while (l + 1 < r) {
    
            int mid = l + (r - l) / 2;
            if (nums[mid] == target) return mid;
            else if (nums[mid] > target) r = mid;
            else l = mid;
        }
        return -1;
    }
};

2:左闭右闭

class Solution {
    
public:
    int search(vector<int>& nums, int target) {
    
       
        int l = 0, r = nums.size() - 1;
        while (l <= r) {
    
            int mid = l + (r - l) / 2;
            if (nums[mid] == target) return mid;
            else if (nums[mid] > target) r = mid - 1;
            else l = mid + 1;
        }
        return -1;
    }
};

3:左开右闭

class Solution {
    
public:
    int search(vector<int>& nums, int target) {
    
   
        int l = -1, r = nums.size() - 1;
        while (l < r) {
    
            int mid = l + (r - l) / 2 + 1;//mid偏向r一边,否则会陷入死循环
            if (nums[mid] == target) return mid;
            else if (nums[mid] > target) r = mid - 1;
            else l = mid;
        }
        return -1;
    }
};

4:左闭右开

class Solution {
    
public:
    int search(vector<int>& nums, int target) {
    
 
        int l = 0, r = nums.size();
        while (l < r) {
    
            int mid = l + (r - l) / 2;
            if (nums[mid] == target) return mid;
            else if (nums[mid] > target) r = mid;
            else l = mid + 1;
        }
        return -1;
    }
};
原网站

版权声明
本文为[重you小垃]所创,转载请带上原文链接,感谢
https://blog.csdn.net/zhangjiaji111/article/details/125601772