codility / traning center [MaxCounters]
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:
class Solution { public int[] solution(int N, 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.
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).
이 문제는 솔직히 말하면 아직도 왜 88%밖에 안나오는지 모르겠다.
report를 보면 시간 복잡도가 조건에 맞는 O(N+M)인데 마지막 문항이 time out이 나왔다.
이 문제를 풀면서 계속 실수를 했던 것은
첫 번째 if에서 maxResult += max; max = 0; 를 안해줬던 것이었다.
계속해서 새로 배열을 만들었는데 아무래도 이 것 때문에 시간이 오래 걸린 것은 아닌가 싶다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public int[] solution(int N, int[] A) { int max = 0; int maxResult = 0; int[] result = new int[N]; for ( int index : A ) { if ( index == N + 1 ) { maxResult += max; result = new int[N]; max = 0; } else { result[index - 1]++; int temp = result[index - 1]; max = max > temp ? max : temp; } } for ( int i = 0; i < N; i ++ ) { result[i] += maxResult; } return result; } | cs |
Test result report - Java
Test result report - Javascript
'--이전중입니다-- > 알고리즘' 카테고리의 다른 글
[LeetCode] 73. Set Matrix Zeroes (2) | 2019.08.03 |
---|---|
codility - GenomicRangeQuery ( java ) (0) | 2018.01.07 |
codility - MinAvgTwoSlice ( javascript ) (0) | 2017.12.31 |