【leetcode】Dichotomy

  1. Dichotomy Left Closed Right Closed

Personal summary: If target==nums[middle] is not placed on the first line, an error may occur, as in the following program

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

Leetcode's official program will also make an error if target==nums[middle] is placed in the last condition.

The following is an error case

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

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

Pay attention to the distinction, in fact, the method of closing left and opening right is basically the same as that of opening left and closing right, and the scope of inclusion is essentially the same, the main thing is not to repeatedly include the middle element. Left closed right open, right=num.size(), because the last element number to be included is num.size()-1. When comparing target<nums[middle], right=middle, because the interval to be compared is [left, middle-1], and middle is not included at this time. In the same way, close left and right, right=num.size()-1. When comparing target<nums[middle], right=middle-1, because the interval to be compared is [left, middle-1], middle is included at this time.

Guess you like

Origin blog.csdn.net/Lccca/article/details/129157427