LC.P2028[找出缺失的观测数据]

方法一:数学

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int[] missingRolls(int[] rolls, int mean, int n) {
int m = rolls.length, s = m + n;
int total = s * mean; // 总和
for (int roll : rolls) total -= roll;
// n个元素的总和范围需在[n, 6 * n]
if (total < n || total > 6 * n) return new int[0];
int[] ans = new int[n];
Arrays.fill(ans, total / n);
int d = total - (total / n * n);
for (int i = 0; d-- > 0; ++i) {
++ans[i];
}
return ans;
}
}
  • 时间复杂度:$O(m + n)$
  • 空间复杂度:$O(n)$