当前位置:网站首页>leetcode704. Binary search (find an element, simple, different writing)

leetcode704. Binary search (find an element, simple, different writing)

2022-07-06 07:03:00 Heavy garbage

 Insert picture description here
 Insert picture description here
The main points of : Always maintain the same interval as the initial position .

1: Left open right open

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: Left and right closed

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: Left open right closed

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 deviation r On one side , Otherwise, it will fall into a dead cycle 
            if (nums[mid] == target) return mid;
            else if (nums[mid] > target) r = mid - 1;
            else l = mid;
        }
        return -1;
    }
};

4: Left closed right away

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;
    }
};
原网站

版权声明
本文为[Heavy garbage]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060654495439.html