You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
classSolution {
public:intsearch(vector<int>& nums, int target) {
int n = nums.size();
int left = 0, right = n;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) left = mid + 1;
else right = mid;
}
if (right >= n || nums[right] != target)
return0;
int start = right;
left = start, right = n;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] <= target) left = mid + 1;
else right = mid;
}
return right-start;
}
};
The text was updated successfully, but these errors were encountered:
统计一个数字在排序数组中出现的次数。
示例 1:
示例 2:
限制:
数组有序,用两次二分查找,第一次找第一个=target的元素,第二次找第一个>target的元素,返回值是两个元素的索引相减。代码如下:
The text was updated successfully, but these errors were encountered: