leetcode/src/s0704_binary_search.cpp

38 lines
680 B
C++
Raw Normal View History

2022-11-24 08:44:36 +00:00
#include "s0704_binary_search.hpp"
// 闭区间写法
2022-11-30 10:20:36 +00:00
int S0704::binSearch1(vector<int>& nums, int target) {
2022-11-24 08:44:36 +00:00
int len = nums.size();
int l{0};
int r = len - 1;
while (l <= r) {
int m = (l + r) >> 1;
if (target < nums[m]) {
r = m - 1;
} else if (nums[m] < target) {
l = m + 1;
} else {
return m;
}
}
return -1;
}
// 开区间写法
2022-11-30 10:20:36 +00:00
int S0704::binSearch2(vector<int>& nums, int target) {
2022-11-24 08:44:36 +00:00
int len = nums.size();
int l{0};
int r = len;
while (l < r) {
int m = (l + r) >> 1;
if (target < nums[m]) {
r = m;
} else if (nums[m] < target) {
l = m + 1;
} else {
return m;
}
}
return -1;
}