leetcode/src/s0704_binary_search.cpp
2022-11-24 16:44:36 +08:00

38 lines
686 B
C++

#include "s0704_binary_search.hpp"
// 闭区间写法
int Solution1::binSearch(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 Solution2::binSearch(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;
}