题目描述:统计一个数字在一个排序数组中出现的次数!
分析:排序数组 ====》 二分查找!
代码:
#include<stdio.h>
// 查找第一个K
int GetFirstK(int *nums, int length, int k)
{
if (nums == NULL || length <= 0)
{
return -1;
}
int pLeft = 0;
int pRight = length - 1;
while (pLeft <= pRight)
{
int index = (pLeft + pRight) / 2;
if (nums[index] == k)
{
//在原来二分查找的基础上添加条件“nums[index - 1] != k)”
if ((index < length - 1 && nums[index - 1] != k) || index == length - 1)
{
return index;
}
else
pRight = index - 1;
}
else if (nums[index] < k)
{
pLeft = index + 1;
}
else
{
pRight = index - 1;
}
}
return -1;
}
// 查找最后一个K
int GetLastK(int *nums, int length , int k)
{
if (nums == NULL || length <= 0)
{
return -1;
}
int pLeft = 0;
int pRight = length -1;
while (pLeft <= pRight)
{
int index = (pLeft + pRight) / 2;
if (nums[index] == k)
{
//在原来二分查找的基础上添加条件“nums[index + 1] != k)”
if ((index < length -1 && nums[index + 1] != k) || index == length -1)
{
return index;
}
else
pLeft = index + 1;
}
else if (nums[index] < k)
{
pLeft = index + 1;
}
else
{
pRight = index - 1;
}
}
return -1;
}
int main()
{
int count = 0;
int nums[] = { 1, 3, 5, 7, 7, 7, 7, 7, 7, 7, 9 };
int first = GetFirstK(nums,11, 7);
int last = GetLastK(nums, 11, 7);
if (first > -1 && last > -1)
{
count = last - first + 1;
}
printf("%d\n", count);
}