在O(1)的时间内计算n个整数落在区间[a,b]的个数
预处理时间为O(n+k)
算法导论第三版8.2-4题
int find_inverter_count(int *array,int length,int maximum,int inverter_left,int inverter_right)
{
if(inverter_left<0 || inverter_right>maximum || inverter_right<inverter_left)
{
perror("inverter error");
return -1;
}
int *count_array = new int[maximum+1];
for (int i = 0; i < maximum+1; ++i) {
count_array[i] = 0;
}
for (int i = 0; i < length; ++i) {
count_array[array[i]] = count_array[array[i]] + 1;
}
for (int i = 1; i < maximum+1; ++i) {
count_array[i] = count_array[i] + count_array[i-1];
}
int count = 0;
if(inverter_left == 0)
count = count_array[inverter_right];
else
count = count_array[inverter_right] - count_array[inverter_left - 1];
delete [] count_array;
return count;
}