题目:统计一个数字在排序数组中出现的次数。例如:输入一个排序数组{1,2,3,3,3,3,4,5} 和数字3,由于3在这个数组中的出现了4次,因此输出4.
1.蛮力法,不考虑数组是排序数组这一特点,从头到尾遍历得到这次数字在数组中出现的次数——时间复杂度O(n),空间复杂度为O(1).
int numberCountsByExhaustion(int* array, int length, int number) {
if (NULL == array || 0 >= length) {
return -1;
}
int count = 0;
for (int i = 0; i < length; ++i) {
if (number == array[i]) {
++count;
}
}
return count;
}
2.利用二分查找法——时间复杂度O(log2n),空间复杂度为O(1).
int numberCountsByBinarySearch(int* array, int length, int number) {
if (NULL == array || 0 >= length) {
return -1;
}
int count = 0;
int left = 0, right = length - 1;
int middle = left + (right - left) / 2;
while (left <= right) {
middle = left + (right - left) / 2;
if (number < array[middle]) {
right = middle - 1;
} else if (number > array[middle]) {
left = middle + 1;
} else {
break;
}
}
for (int i = middle; i >= 0; --i) {
if (number == array[i]) {
++count;
} else {
break;
}
}
for (int i = middle + 1; i < length; ++i) {
if (number == array[i]) {
++count;
} else {
break;
}
}
return count;
}
测试代码
/*
*
* Created on: 2014-4-8 20:59:35
* Author: danDingCongRong
*/
#include<iostream>
using namespace std;
//输入各个数组元素
void inputArray(int* array, int length) {
cout << "输入这个数组中的各个数字:" << endl;
for (int i = 0; i < length; ++i) {
cin >> array[i];
}
}
int main() {
int length = 0;
cout << "请输入数组的长度:" << endl;
cin >> length;
int* x = new int[length];
inputArray(x, length);
int findNumber = 0;
cout << "输入要查找的数字:" << endl;
while (cin >> findNumber) {
cout << "暴力查找得到的次数:" << numberCountsByExhaustion(x, length, findNumber)
<< endl;
cout << "二分法得到的次数:" << numberCountsByBinarySearch(x, length, findNumber)
<< endl;
cout << "输入要查找的数字:" << endl;
}
delete x;
return 0;
}
注:部分内容参考自剑指offer