编辑
2023-10-19
后端
00
请注意,本文编写于 617 天前,最后修改于 617 天前,其中某些信息可能已经过时。

目录

左边界 Binary Search 模板:
右边界 Binary Search 模板:
左边界 Binary Search 模板:
右边界 Binary Search 模板:

当你需要找到一个有序数组中某个元素的左边界和右边界时,可以使用以下两个模板。这里我提供一个通用的模板,适用于不同数据类型:

cpp
#include <iostream> #include <vector> template <typename T> int leftBound(const std::vector<T>& array, T target) { int left = 0; int right = array.size(); // 注意这里右边界初始化为数组大小 while (left < right) { int mid = left + (right - left) / 2; if (array[mid] < target) { left = mid + 1; } else { right = mid; } } return left; // 返回左边界 } int main() { // 示例用法 std::vector<int> sortedArray = {1, 2, 2, 2, 3, 4, 4, 5}; int target = 2; int leftBoundIndex = leftBound(sortedArray, target); std::cout << "Left bound of " << target << ": " << leftBoundIndex << std::endl; return 0; }
cpp
#include <iostream> #include <vector> template <typename T> int rightBound(const std::vector<T>& array, T target) { int left = 0; int right = array.size(); // 注意这里右边界初始化为数组大小 while (left < right) { int mid = left + (right - left) / 2; if (array[mid] <= target) { left = mid + 1; } else { right = mid; } } return left - 1; // 返回右边界 } int main() { // 示例用法 std::vector<int> sortedArray = {1, 2, 2, 2, 3, 4, 4, 5}; int target = 2; int rightBoundIndex = rightBound(sortedArray, target); std::cout << "Right bound of " << target << ": " << rightBoundIndex << std::endl; return 0; }

这两个模板都使用了二分查找的思想,通过调整左右边界来确定左边界或右边界的位置。在实际应用中,这两个模板非常有用,可以帮助你解决一些查找范围的问题。

以下是 Go 语言版本的二分查找左右边界的模板:

go
package main import "fmt" func leftBound(nums []int, target int) int { left, right := 0, len(nums) for left < right { mid := left + (right-left)/2 if nums[mid] < target { left = mid + 1 } else { right = mid } } return left // 返回左边界 } func main() { // 示例用法 sortedArray := []int{1, 2, 2, 2, 3, 4, 4, 5} target := 2 leftBoundIndex := leftBound(sortedArray, target) fmt.Printf("Left bound of %d: %d\n", target, leftBoundIndex) }
go
package main import "fmt" func rightBound(nums []int, target int) int { left, right := 0, len(nums) for left < right { mid := left + (right-left)/2 if nums[mid] <= target { left = mid + 1 } else { right = mid } } return left - 1 // 返回右边界 } func main() { // 示例用法 sortedArray := []int{1, 2, 2, 2, 3, 4, 4, 5} target := 2 rightBoundIndex := rightBound(sortedArray, target) fmt.Printf("Right bound of %d: %d\n", target, rightBoundIndex) }

这两个 Go 版本的模板与之前的 C++ 版本相似,使用了二分查找的思想。在 Go 中,切片的索引范围是左闭右开的,因此在返回左边界和右边界时需要注意索引的差异。

本文作者:yowayimono

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!