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 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:
class Solution { public int[] solution(int N, int[] A); }
that, given an integer N and a non-empty array A consisting of M integers, returns a sequence of integers representing the values of the counters.
Result array should be returned as an array of integers.
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.
Write an efficient algorithm for the following assumptions:
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].
풀어보려고 일단 노력했다. 문제가 되는 부분은 아마 Array로 부터 maxCounter를 얻고, 각 Array에 그 숫자를 A[K] = N + 1 조건에 채워주려 했던 부분에 문제가 되지 않을까 했는데 역시나 실패했다. 시간 복잡도 O(N)으로 풀어야 풀이가 가능하리라 생각한다.
class Solution {
public int[] solution(int N, int[] A) {
int[] result = new int[N];
for(int i=0; i<A.length; i++) {
int resultIndex = A[i];
if ((N+1) == resultIndex) {
int maxCounter = getMaxCounterFromIntArray(result);
for(int j=0; j<N; j++) {
result[j] = maxCounter;
}
} else {
result[resultIndex-1]++;
}
}
return result;
}
private int getMaxCounterFromIntArray(int[] A) {
int maxCounter = 0;
for(int i : A) {
if (maxCounter < i) {
maxCounter = i;
}
}
return maxCounter;
}
}
좋은 답안의 예중 하나다.max 값을 결과 배열 할당하면서 변수에 계속 담고, Math.max로 비교해서 가지고 결과 배열의 카운트를 먼저 증감시켜 비교하였다.
또 Array.fill method를 통해 for루프 돌리지 않고 빠르게 값을 채워주었다.
엥? 근데 이것도 퍼포먼스에서 실패한다.
public int[] solution(int N, int[] A) {
int len = A.length;
int max = 0;
int[] result = new int[N];
for(int i=0; i<len; i++){
if(A[i] == N+1){
Arrays.fill(result,max);
}else{
max = Math.max(max,++result[A[i]-1]);
}
}
return result;
}
아래와 같이 계산하여 퍼포먼스 100을 이끌어낸 답이 있다.
function solution(N, A) {
let counters = [];
let max = 0;
let lastMax = 0;
for(let i=0; i<N; i++){
counters[i] = 0;
}
for(let K in A){
let X = A[K];
if(X <= N){
if(counters[X-1] < lastMax){
counters[X-1] = lastMax;
}
counters[X-1]++;
if(max < counters[X-1]){
max = counters[X-1];
}
}
else{
lastMax = max;
}
}
for(let i=0; i<N; i++){
if(counters[i] < lastMax){
counters[i] = lastMax;
}
}
return counters;
}