您的位置:首页 > 移动开发 > IOS开发

在排序数组中,找出给定数字的出现次数

2012-08-27 19:44 381 查看
from: http://blog.csdn.net/yake25/article/details/7346249

#include <iostream>
#include <vector>
#include <fstream>
#include <ctime>
using namespace std;

int low(vector<int> &ivec, int left, int right, int x)
{
while(left < right)
{
int mid = (left + right) / 2;
if(ivec[mid] < x)
left = mid + 1;
else
right = mid;
}
return left;
}

int upper(vector<int> &ivec, int left, int right, int x)
{
while(left < right)
{
int mid = (left + right) / 2;
if(ivec[mid] > x)
right = mid;
else
left = mid + 1;
}
return right;
}

int main()
{
clock_t begin = clock();
int n, x, left, right, first = 0, last = 0;
vector<int> ivec;
ifstream infile("input2.txt");
while(infile >> n)
ivec.push_back(n);
cout << "Input x: " << endl;
cin >> x;
left = 0;
right = ivec.size();
while(left < right)
{
int mid = (left + right) / 2;
if(ivec[mid] < x)
left = mid + 1;
else if(ivec[mid] > x)
right = mid + 1;
else
{
first = low(ivec, left, right, x);
cout << first << endl;
last = upper(ivec, left, right, x);
break;
}
}
cout << "Numbers: " << last - first << endl;
clock_t endtime = clock();
cout << "Time: " << (double)(endtime - begin) << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐