1 class Solution { 2 public: 3 // 查找第一个小于等于target的值 4 int binarySearch1(vector<int> vec, int target) { 5 int left = 0; 6 int right = vec.size() - 1; 7 while (left <= right) { 8 int mid = left + (right - left) / 2; 9 if (vec[mid] > target) { // 目标值可能在区间[left, mid] 10 right = mid - 1; 11 } else { // 目标值可能在区间[mid, right] 12 left = mid + 1; 13 } 14 } 15 return right; 16 } 17 // 查找第一个大于等于target的值 18 int binarySearch2(vector<int> vec, int target) { 19 int left = 0; 20 int right = vec.size() - 1; 21 while (left <= right) { 22 int mid = left + (right - left) / 2; 23 if (vec[mid] < target) { // 目标值可能在区间[mid, right] 24 left = mid + 1; 25 } else { // 目标值可能在区间[left mid] 26 right = mid - 1; 27 } 28 } 29 return right; 30 } 31 // 查找等于target的值 32 int binarySearch3(vector<int> vec, int target) { 33 int left = 0; 34 int right = vec.size() - 1; 35 while (left <= right) { 36 int mid = left + (right - left) / 2; 37 if (vec[mid] == target) { 38 return mid; 39 } else if (vec[mid] > target) { // 目标值可能在区间[left, mid] 40 right = mid - 1; 41 } else { // 目标值可能在区间[mid, right] 42 left = mid + 1; 43 } 44 } 45 return -1; 46 } 47 };