题目
统计一个数字在排序数组中出现的次数。
解答
二分查找
class Solution {
public:
int search(vector<int>& nums, int target) {
int i = 0, j = nums.size() - 1;
int pos = -1;
while (i <= j) {
pos = (i + j) / 2;
if (nums[pos] > target)
j = pos - 1;
else if (nums[pos] < target)
i = pos + 1;
else
break;
}
int cnt = i <= j;
if (i < j) {
i = pos - 1;
while (i >= 0 && nums[i] == target) {
++cnt;
--i;
}
i = pos + 1;
while (i < nums.size() && nums[i] == target) {
++cnt;
++i;
}
}
return cnt;
}
};