You are given N counters, initially set to 0, and you have two possible operations on them:
increase(X) − counter X is increased by 1,
max counter − all counters are set to the maximum value of any counter.
A non-empty zero-indexed array A of M integers is given. This array represents consecutive operations:
if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
if A[K] = N + 1 then operation K is max counter.
For example, given integer N = 5 and array A such that:
A[0] = 3
A[1] = 4
A[2] = 4
A[3] = 6
A[4] = 1
A[5] = 4
A[6] = 4
the values of the counters after each consecutive operation will be:
(0, 0, 1, 0, 0)
(0, 0, 1, 1, 0)
(0, 0, 1, 2, 0)
(2, 2, 2, 2, 2)
(3, 2, 2, 2, 2)
(3, 2, 2, 3, 2)
(3, 2, 2, 4, 2)
The goal is to calculate the value of every counter after all operations.
Assume that the following declarations are given:
struct Results {
int * C;
int L;
};
Write a function:
struct Results solution(int N, int A[], int M);
that, given an integer N and a non-empty zero-indexed array A consisting of M integers, returns a sequence of integers representing the values of the counters.
The sequence should be returned as:
a structure Results (in C), or
a vector of integers (in C++), or
a record Results (in Pascal), or
an array of integers (in any other programming language).
For example, given:
A[0] = 3
A[1] = 4
A[2] = 4
A[3] = 6
A[4] = 1
A[5] = 4
A[6] = 4
the function should return [3, 2, 2, 4, 2], as explained above.
Assume that:
N and M are integers within the range [1..100,000];
each element of array A is an integer within the range [1..N + 1].
Complexity:
expected worst-case time complexity is O(N+M);
expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Solution
struct Results solution(int N, int A[], int M) {
struct Results result;
// write your code in C99
int *count =NULL;
count = calloc(N,sizeof(int));
if(count==NULL){
result.C = NULL;
result.L = 0;
}
for(int i=0; i<N; i++){
count[i]=0;
}
int curMaxCount=0;
int triggerCount=0;
for(int i=0; i<M; i++){
if(A[i]>N) {
triggerCount=curMaxCount;
}
else{
if(count[A[i]-1] < triggerCount){
count[A[i]-1] = triggerCount;
}
count[A[i]-1]+=1;
if(count[A[i]-1]>curMaxCount){
curMaxCount = count[A[i]-1];
}
}
}
for(int i=0; i<N; i++){
if(count[i]<triggerCount) count[i]=triggerCount;
}
result.C = count;
result.L = N;
return result;
}
点评
还是点评一下。
本系列都是统计数组中数据是否出现或出现的次数,在这基础上又出现限制条件。我们需要增加变量记住这些变化,尽量一次遍历完成。
小青蛙跳河是找什么时候可以集齐龙珠,比如龙珠有7颗,那就每找到一颗标记一下。
MaxCounter需要记录当前最大的count,这比较容易想到。但是如果每出现一次N+1就把数组所有元素+1,效率太差。用一个变量将当前最大的count记住,当有更新的时候一起更新。最后检查结果数组,更新那些在触发后再也没有更新的元素。
再吐槽一下C语言内存分配calloc,导致代码不漂亮. 以后用java咯