LeetCode刷题笔记之二分查找

LeetCode刷题笔记之二分查找

二分查找

二分查找需要注意的点大致有以下几点:

  • 注意左右边界的区间,是左闭右开还是左闭右闭,不同的区间对应下文的代码不同。
  • 二分查找查找的是左右边界还是具体的位置,不同的情况对应的代码不同。
  • 理解记忆

寻找一个数的二分查找

int binarySearch(vector<int> &nums, int target) { 
    int left = 0;
    int right = nums.size();
    while (left < right) { //区间是左闭右开
        int mid = left + (right - left) / 2;
        if (nums[mid] == target) {
            return mid;
        } else if (nums[mid] > target) {
            right = mid; //对应区间的
        } else if(nums[mid] > target) {
            left = left + 1
        }
    }
    return -1;
}

寻找一个数的左侧边界

int left_bound(vector<int> nums, int target) {
    if (nums.size() == 0) return -1;
    int left =0, right = nums.size();
    
    while (left < right) { // 左闭右开区间
        int mid = left + (right - left) / 2;
        if (nums[mid] == target) {
            right = mid;
        } else if (nums[mid] > target) {
            right = mid;
        } else if (nums[mid] < target) {
            left = mid + 1;
        }
    }
    if (left == nums.size()) return -1;
    return nums[left] == target ? left : -1;
}

int left_bound(vector<int> &nums, int target) {
    int left = 0, right = nums.size() - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] == target) {
            right = mid - 1;
        } else if (nums[mid] > target) {
            right = mid - 1;
        } else if (nums[mid] < target) {
            left = mid + 1;
        }
    }
    if (left >= nums.size() || nums[left] != target) {
        return -1;
    }
    return left;
}

寻找一个数的右侧边界

int right_bound(vector<int> &nums, int target) {
    if (nums.size() == 0) return -1;
    int left = 0, right = nums.size();
    
    while (left < right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] == target) {
            left = mid + 1;
        } else if (nums[mid] > target) {
            right = mid;
        } else if (nums[mid] < target) {
            left = mid + 1;
        }
    }
    if (left == 0) return -1;
    return nums[left - 1] == target ? (left - 1) : -1;
}

int right_bound(vector<int> &nums, int target) {
    int left = 0, right = nums.size() - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] == target) {
            left = mid +1;
        } else if (nums[mid] > target) {
            right = mid - 1;
        } else if (nums[mid] < target) {
            left = mid + 1;
        }
    } 
    if (right < 0 || nums[right] != target) return -1;
    return right;
}
posted @ 2022-02-21 18:03  IU_UI  阅读(45)  评论(0编辑  收藏  举报