问题描述
嗨,天才,祝你有美好的一天 情况:
T [M] an array sorts in ascending order.
Write an algorithm that calculates the number of occurrences of an integer x in the array T[M].
the number of comparison of x to the elements of T,must be of order log n
我的尝试是:
def Occurrence(T,X,n):{
if ( n=0 ){ return 0;}
else {
Occurrence(T,n/2);
if( T[n]==X ){ return 1+Occurrence(T,x,n/2); }
else { return Occurrence(T,n/2); }
}the end of code
complexity is :
0 if n=0
we have O(n)={
1+O(n/2) if n>0
O(n)=1+1+1+....+O(n/2^(n))=n+O(2/2^(n))
when algorithm stopp if{existe k n=2^(k),so O(n)=n+1 }
n/2^(n)=1) => O(n)=log(n)+1,so you think my code is true ?
</pre>
解决方法
查看 binary search variants 给出所需元素的最左边和最右边的索引,然后返回 index_difference + 1
您可以在 C++ STL 中使用 lower_bound
和 upper_bound
,在 Python 中使用 bisect_left
和 bisect_right
,类似的函数(如果有),或者实现来自 Wiki 引用的伪代码。
如果数组已排序
import bisect
T = [1,3,4,6,7]
x = 4
right = bisect.bisect(T,x)
if(right == 0 or T[right - 1] != x):
print("Count:0")
else:
left = bisect.bisect_left(T,x)
print("Count:",right - left)
2Log(n)