数字在升序数组中出现的次数(upper_bound & lower_bound)
数字在升序数组中出现的次数
http://www.nowcoder.com/questionTerminal/70610bf967994b22bb1c26f9ae901fa2
/* 返回迭代器 对应数组下标要-vt.begin() upper_bound(vt.begin(),vt.end(), value)返回第一个大于查找数字下标 lower_bound()返回第一个大于等于查找数的下标 */ int GetNumberOfK(vector<int> nums ,int target) { return upper_bound(nums.begin(), nums.end(), target) - lower_bound(nums.begin(), nums.end(), target); }
class Solution { public: int GetNumberOfK(vector<int> nums ,int target) { int lbound = 0, rbound = 0; // lower_bound() int low = 0, high = nums.size(); while (low < high) { int mid = low + (high - low) / 2; nums[mid] < target? low = mid + 1:high = mid; } lbound = low; // upper_bound() 返回第一个大于查找数字下标 low = 0, high = nums.size(); while (low < high) { int mid = low + (high - low) / 2; nums[mid] <= target? low = mid + 1: high = mid; } rbound = low; return rbound - lbound; } };