我希望提高我算法的运行时间,算法的目标是计算输入数组中0的总数。输入数组长度为n,由排序好的0和1组成。
目前我的算法是:
Algorithm : zeroCount(A)
Input : An sorted array A containing 0s and 1s
Output : total number of 0s in A
if A[0]=1 then
return 0;
len <— A.length
if A[len-1]=0 then
return len
count <— 0
i <—0
for i<len do
if A[i]==0 then
count++
i++
return count
Java的实现如下:
public int zeroCount(int[] a){
if(a[0]==1)
return 0;
int length =a.length;
if(a[length-1]==0)
return length;
int count=0;
for(int i=0;i<length&&a[i]==0;i++){
count++;
}
return count;
}
然而,该算法的运行时间为O(n)。如有任何改进该算法以提高运行时间的建议,将不胜感激。