Codility- MaxCounters

来源:互联网 发布:it便利店 编辑:程序博客网 时间:2024/05/20 10:11

Task description

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.

Write a function:

vector<int> solution(int N, vector<int> &A);

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.

题意很简单,就是将一个数组按照A数组里的数对一个长度为N的计数器进行一系列操作,如果A[i]小于N则将计数器中对应位置的数+1,如果A[i]大于N则将计数器中所有的数更新为计数器当前的最大值,题目里面描述的很明白

对与这样一题看上去会很容易做,但要求的时间复杂度是O(N+M),空间复杂度是O(N)(codility跟别的oj不太一样,不是告诉你限制多少秒而是告诉你最差的时间复杂度和空间复杂度可以是多少),所以一般的模拟不太容易解决
但是收到O(N+M)的启发,突然想到在遍历A数组的时候同时更新计数器,当A中某个数大于N时,记录下当前的最大值,然后再后面的遍历中更新计数器时,判断计数器是否小于之前记录的更新值,如果小于 则更新为:之前记录的更新值+1 最后再遍历一遍计数器将那些小于更新值的数全都置为更新值就可解决问题

vector<int> solution(int N, vector<int> &A) {    // write your code in C++14 (g++ 6.2.0)    int len = A.size(),nmax = 0,amax = 0;//nmax:上一次的更新值,amax:当前数组的最大值    vector<int> ans;    ans.assign(N,0);//初始化ans数组(或者说容器?数组好像不太准确…)    for(int i=0;i<len;i++){        if(A[i]<=N){            if(ans[A[i]-1]<nmax) ans[A[i]-1] = nmax+1;//若小于更新值则置为更新值+1            else ans[A[i]-1]++;//否则自增1即可            amax = max(amax,ans[A[i]-1]);        }else nmax =amax;//若大于N则将更新值记录为当前数组的最大值    }    for(int i=0;i<N;i++){        if(ans[i]<nmax) ans[i] = nmax;    }    return ans;}
原创粉丝点击