int BinarySearch(int* nums, int numsSize, int target)
{
int left = 0, right = numsSize - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (nums[mid] > target)
{
right = mid - 1;
}
else if (nums[mid] < target)
{
left = mid + 1;
}
else
{
return mid;
}
}
return -1;
}
int search(int* nums, int numsSize, int target) {
int count = 0;
int index = BinarySearch(nums, numsSize, target);
if (index == -1)
{
return count;
}
else
{
count++;
}
int left=index-1,right=index+1;
while (left >= 0&&nums[left] == target)
{
count++;
left--;
}
while (right < numsSize&&nums[right] == target)
{
count++;
right++;
}
return count;
}
我们考虑怎样更好地利用二分查找,在前面的算法中,时间主要消耗在一个一个找target,从而找到第一个target和最后一个target上,所以我们能不能用通过某种方式更快地直接找到第一个target和最后一个target。
int GetFirstOfK(int* nums, int numsSize, int target)
{
int left = 0, right = numsSize - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (nums[mid] > target)
{
right = mid - 1;
}
else if (nums[mid] < target)
{
left = mid + 1;
}
else
{
if (mid-1>=0&&nums[mid - 1] != target || mid==0)//关键边界处理
{
return mid;
}
else
{
right = mid - 1;
}
}
}
return -1;
}
int GetLastOfK(int* nums, int numsSize, int target)
{
int left = 0, right = numsSize - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (nums[mid] > target)
{
right = mid - 1;
}
else if (nums[mid] < target)
{
left = mid + 1;
}
else
{
if (mid + 1 <numsSize && nums[mid + 1] != target||mid==numsSize-1)
{
return mid;
}
else
{
left = mid + 1;
}
}
}
return -1;
}
int search(int* nums, int numsSize, int target) {
int count = 0;
int first = GetFirstOfK(nums, numsSize, target);
int last = GetLastOfK(nums, numsSize, target);
if (first != -1 && last != -1)
{
return last - first + 1;
}
return count;
}