数组中数字的出现,具有复杂的log n算法和c
Occurrence of number in array,with complexity log n algorithm and c
嗨,天才,祝你有美好的一天
情况:
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,X,n/2);
if( T[n]==X ){ return 1+Occurrence(T,x,n/2); }
else { return Occurrence(T,x,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 给出所需元素的最左边和最右边的索引,然后 return index_difference + 1
您可以在 C++ STL 中使用 lower_bound
和 upper_bound
,在 Python 中使用 bisect_left
和 bisect_right
,如果有类似的功能,或者从维基引用。
如果数组已排序
import bisect
T = [1, 3, 4, 4, 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)
嗨,天才,祝你有美好的一天 情况:
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,X,n/2);
if( T[n]==X ){ return 1+Occurrence(T,x,n/2); }
else { return Occurrence(T,x,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 给出所需元素的最左边和最右边的索引,然后 return index_difference + 1
您可以在 C++ STL 中使用 lower_bound
和 upper_bound
,在 Python 中使用 bisect_left
和 bisect_right
,如果有类似的功能,或者从维基引用。
如果数组已排序
import bisect
T = [1, 3, 4, 4, 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)