剑指 Offer 53 - I. 在排序数组中查找数字 I
1、直观感受,二分找到Target位置,然后向两边扩展计数。
class Solution {
public:
int numPosition(vector<int>& nums, int target)
{
int left = 0;
int right = nums.size();
int mid = left + (right - left)/2;
while (left < right)
{
if (nums[mid] == target)
return mid;
if (target > nums[mid])
{
left = mid + 1;
}
else
{
right = mid;
}
mid = left + (right - left)/2;
}
return -1;
}
int search(vector<int>& nums, int target)
{
int pos = numPosition(nums, target);
if (pos < 0)
{
return 0;
}
int temp = pos;
int count = 0;
while (temp >= 0 && nums[temp--] == target)
count++;
temp = pos + 1;
while (temp < nums.size() && nums[temp++] == target)
count++;
return count;
}
};
2、二分优化,直接找两端
class Solution {
public:
int binarySearch(vector<int>& nums, int target, bool lower)
{
int left = 0, right = (int)nums.size() - 1, ans = (int)nums.size();
while (left <= right)
{
int mid = (left + right) / 2;
if (nums[mid] > target || (lower && nums[mid] >= target))
{
right = mid - 1;
ans = mid;
}
else
{
left = mid + 1;
}
}
return ans;
}
int search(vector<int>& nums, int target)
{
int leftIdx = binarySearch(nums, target, true);
int rightIdx = binarySearch(nums, target, false) - 1;
if (leftIdx <= rightIdx && rightIdx < nums.size() && nums[leftIdx] == target && nums[rightIdx] == target)
{
return rightIdx - leftIdx + 1;
}
return 0;
}
};
|