微软的面试题。。。感觉好高大上的样子
我想的比较简单粗暴
l = [2, 3, 6, 6, 6, 9]
count = 0
for x in l:
if x == 6:
count += 1
print(count)
当然对于已排序的数组,无疑二分查找更高效
#include <iostream>
#include <vector>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#include <cstdio>
#define MAX 500010
using namespace std;
int getUpper(int arr[], int left, int right, int key)
{
while(left < right)
{
int mid = (left + right + 1) / 2;
if (arr[mid] <= key)
return getUpper(arr, mid, right, key);
else
return getUpper(arr, left, mid - 1, key);
}
return left;
}
int getLower(int arr[], int left, int right, int key)
{
while(left < right)
{
int mid = (left + right) / 2;
if (arr[mid] >= key)
return getLower(arr, left, mid, key);
else
return getLower(arr, mid + 1, right, key);
}
return right;
}
int main(void)
{
int a[6] = {2, 3, 6, 6, 6, 9};
cout << getUpper(a, 0, 5, 6) - getLower(a, 0, 5, 6) + 1 << endl;
return 0;
}
这里用了两个函数,一个向左找,一个向右找