java codility Max-Counters
我一直在尝试解决以下任务:
您将获得 N 个计数器,最初设置为 0,并且对它们有两个可能的操作:
increase(X) − counter X is increased by 1,
max_counter − all counters are set to the maximum value of any counter.
给出了一个包含 M 个整数的非空零索引数组 A。此数组表示连续操作:
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.
例如,给定整数 N = 5 和数组 A,使得:
A[0] = 3
A[1] = 4
A[2] = 4
A[3] = 6
A[4] = 1
A[5] = 4
A[6] = 4
每次连续操作后的计数器值将为:
(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)
目标是在所有操作后计算每个计数器的值。
struct Results {
int * C;
int L;
};
编写一个函数:
struct Results solution(int N, int A[], int M);
给定一个整数 N 和一个由 M 个整数组成的非空零索引数组 A,返回一个表示计数器值的整数序列。
该序列应返回为:
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).
例如,给定:
A[0] = 3
A[1] = 4
A[2] = 4
A[3] = 6
A[4] = 1
A[5] = 4
A[6] = 4
该函数应返回 [3, 2, 2, 4, 2],如上所述。
假设:
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].
复杂性:
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).
可以修改输入数组的元素。
这是我的解决方案:
import java.util.Arrays;
class Solution {
public int[] solution(int N, int[] A) {
final int condition = N + 1;
int currentMax = 0;
int countersArray[] = new int[N];
for (int iii = 0; iii < A.length; iii++) {
int currentValue = A[iii];
if (currentValue == condition) {
Arrays.fill(countersArray, currentMax);
} else {
int position = currentValue - 1;
int localValue = countersArray[position] + 1;
countersArray[position] = localValue;
if (localValue > currentMax) {
currentMax = localValue;
}
}
}
return countersArray;
}
}
以下是代码评估:https://codility.com/demo/results/demo6AKE5C-EJQ/
你能给我一个提示这个解决方案有什么问题吗?