LC.P1894[找到需要补充粉笔的学生编号]

方法一:模拟

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int chalkReplacer(int[] chalk, int k) {
int n = chalk.length;
long sum = 0;
for (int c : chalk) sum += c;
k = (int) (k % sum);
for (int i = 0; i < n; ++i) {
k -= chalk[i];
if (k < 0) return i;
}
return -1;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$