您的位置:首页 > Web前端

【剑指offer】数字在排序数组中出现的次数

2013-09-02 16:49 465 查看
2013-09-02 16:28:35

找出数字在排序数组中出现的次数。

注意几点:

一开始试图用size_t类型表示数组的下标begin、end,到那时这样做在end = 0时,end - 1是size_t类型的最大值,仍然满足begin <= end,但此时将会对sortedArray数组中下标为size_t类型的最大值的元素,会出现访问越界;因此,对于数组小标,不要为了保证是整数二用size_t类型,用int类型比较好。

若用int型表示,就不需要用STATUS的状态标志,下面的程序中没有修改这一点。

代码:

#include <iostream>
#include <cassert>
using namespace std;

typedef int DataType;

const bool SuccessToFind = true;
const bool FailToFind = false;

bool STATUS = SuccessToFind;

//找出第一个K出现的位置的下标
int GetFirstK(DataType *sortedArray,int begin,int end,const DataType data)
{
/*assert(NULL != sortedArray);
assert(begin <= end);*/

STATUS = FailToFind;
int mid = 0;

while (begin <= end)
{
mid = begin + (end - begin) / 2;
if (sortedArray[mid] == data)
{
if (mid == begin || sortedArray[mid - 1] != data)
{
STATUS = SuccessToFind;
return mid;
}
else
{
end = mid - 1;
}
}
else if (sortedArray[mid] < data)
{
begin = mid + 1;
}
else
{
end = mid - 1;   //mid为0时,若end为size_t类型,会出错
}
}

STATUS = FailToFind;
return 0;
}

//找出最后一个K出现的位置的下标
int GetLastK(DataType *sortedArray,int begin,int end,const DataType data)
{
/*assert(NULL != sortedArray);
assert(begin <= end);*/

STATUS = FailToFind;
int mid = 0;

while (begin <= end)
{
mid = begin + (end - begin) / 2;
if (sortedArray[mid] == data)
{
if (mid == end || sortedArray[mid + 1] != data)
{
STATUS = SuccessToFind;
return mid;
}
else
{
begin = mid + 1;
}
}
else if (sortedArray[mid] < data)
{
begin = mid + 1;
}
else
{
end = mid - 1;
}
}

STATUS = FailToFind;
return 0;
}

//返回K出现的次数
int GetNumberOfK(DataType *sortedArray,int len,const DataType data)
{
assert(NULL != sortedArray);
assert(len >= 1);

size_t begin = GetFirstK(sortedArray,0,len - 1,data);
size_t end = GetLastK(sortedArray,0,len - 1,data);

if (STATUS == SuccessToFind)
{
return (end - begin + 1);
}
else
{
return 0;
}
}

//测试GetNumberOfK
void TestGetNumberOfK()
{
DataType sortedArray[10] = {1,2,3,3, 3,3,4,4, 5,6};
size_t len = 10;
DataType data = 0;

cout<<"please enter the data to find ,end with ctrl+z "<<endl;
while (cin>>data)
{
cout<<"the number of "<<data<<" in array is : "<<GetNumberOfK(sortedArray,len,data)<<endl;
cout<<"please enter the data to find ,end with ctrl+z "<<endl;
}

}

int main()
{
TestGetNumberOfK();
return 0;
}


测试结果:

please enter the data to find ,end with ctrl+z
3
the number of 3 in array is : 4
please enter the data to find ,end with ctrl+z
4
the number of 4 in array is : 2
please enter the data to find ,end with ctrl+z
2
the number of 2 in array is : 1
please enter the data to find ,end with ctrl+z
1
the number of 1 in array is : 1
please enter the data to find ,end with ctrl+z
-1
the number of -1 in array is : 0
please enter the data to find ,end with ctrl+z
90
the number of 90 in array is : 0
please enter the data to find ,end with ctrl+z
^Z
请按任意键继续. . .
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: