一、寻找排序数组中的一个数(基本的二分搜索),如果存在,返回其索引,否则返回 -1。
1 int binary_search(vector<int>& nums, int target) 2 { 3 if(nums.empty()) return -1; 4 int low = 0; 5 int high = nums.size()-1;// 6 while(low <= high)// 7 { 8 int mid = low +(high-low)/2;//防止溢出 9 if(nums[mid] < target) 10 { 11 low = mid +1; 12 } 13 else if(nums[mid] > target) 14 { 15 high = mid - 1; 16 } 17 else if(nums[mid] == target) 18 { 19 //找到一个即可,找到就立即返回 20 return low; 21 } 22 } 23 return -1; 24 }
二. 寻找左侧边界的二分查找
1 int left_bound( vector<int>& nums, int target) 2 { 3 if(nums.empty()) return -1; 4 int low = 0,high = nums.size()-1; 5 while(low <= high) 6 { 7 int mid = low +(high-low)/2;//防止溢出 8 if(nums[mid] < target) 9 { 10 low = mid +1; 11 } 12 else if(nums[mid] > target) 13 { 14 high = mid - 1; 15 } 16 else if(nums[mid] == target) 17 { 18 // 别返回,收紧右侧边界以锁定左侧边界 19 high = mid - 1; 20 } 21 } 22 //最后要检查low 越界的情况 23 if(low >= nums.size() || nums[low] != target) 24 { 25 return -1; 26 } 27 28 return low; 29 }
三. 寻找右侧边界的二分查找
int right_bound( vector<int>& nums, int target) { if(nums.empty()) return -1; int low = 0,high = nums.size()-1; while(low <= high) { int mid = low +(high-low)/2;//防止溢出 if(nums[mid] < target) { low = mid +1; } else if(nums[mid] > target) { high = mid - 1; } else if(nums[mid] == target) { //不返回 收紧左侧边界以锁定右侧边界 low = mid + 1; } } //验证 high 越界情况 if(high < 0 || nums[high] != target) { return -1; } return high; }