leetcode/src/s0704_binary_search.cpp
2022-11-30 18:20:36 +08:00

38 lines
680 B
C++

#include "s0704_binary_search.hpp"
// 闭区间写法
int S0704::binSearch1(vector<int>& nums, int target) {
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;
}
// 开区间写法
int S0704::binSearch2(vector<int>& nums, int target) {
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;
}