[LeetCode] 2028. Find Missing Observations
You have observations of n + m 6-sided dice rolls with each face numbered from 1 to 6. n of the observations went missing, and you only have the observations of m rolls. Fortunately, you have also calculated the average value of the n + m rolls.
You are given an integer array rolls of length m where rolls[i] is the value of the ith observation. You are also given the two integers mean and n.
Return an array of length n containing the missing observations such that the average value of the n + m rolls is exactly mean. If there are multiple valid answers, return any of them. If no such array exists, return an empty array.
The average value of a set of k numbers is the sum of the numbers divided by k.
Note that mean is an integer, so the sum of the n + m rolls should be divisible by n + m.
Example 1:
Input: rolls = [3,2,4,3], mean = 4, n = 2
Output: [6,6]
Explanation: The mean of all n + m rolls is (3 + 2 + 4 + 3 + 6 + 6) / 6 = 4.
Example 2:
Input: rolls = [1,5,6], mean = 3, n = 4
Output: [2,3,2,2]
Explanation: The mean of all n + m rolls is (1 + 5 + 6 + 2 + 3 + 2 + 2) / 7 = 3.
Example 3:
Input: rolls = [1,2,3,4], mean = 6, n = 4
Output: []
Explanation: It is impossible for the mean to be 6 no matter what the 4 missing rolls are.
Constraints:
m == rolls.length
1 <= n, m <= 105
1 <= rolls[i], mean <= 6
找出缺失的观测数据。
现有一份 n + m 次投掷单个 六面 骰子的观测数据,骰子的每个面从 1 到 6 编号。观测数据中缺失了 n 份,你手上只拿到剩余 m 次投掷的数据。幸好你有之前计算过的这 n + m 次投掷数据的 平均值 。给你一个长度为 m 的整数数组 rolls ,其中 rolls[i] 是第 i 次观测的值。同时给你两个整数 mean 和 n 。
返回一个长度为 n 的数组,包含所有缺失的观测数据,且满足这 n + m 次投掷的 平均值 是 mean 。如果存在多组符合要求的答案,只需要返回其中任意一组即可。如果不存在答案,返回一个空数组。
k 个数字的 平均值 为这些数字求和后再除以 k 。
注意 mean 是一个整数,所以 n + m 次投掷的总和需要被 n + m 整除。
思路
这是一道数学题。已知 m 次的投掷数据和 n + m 次投掷数据的平均值,要求返回的是剩下 n 次的投掷数据,如果存在多组符合要求的答案,只需要返回其中任意一组即可。
设n + m 次投掷数据的总和是 totalSum,已知的 m 次投掷数据的总和是 curSum,那么剩下的 n 次投掷数据的总和是 restSum = totalSum - curSum。如果 restSum < n 或 restSum > 6 * n,则不存在答案,返回空数组。
一般的 case 是我们用 restSum / n 得到一个商 quotient 和一个余数 remainder,那么对于最后需要输出的数组 res,每一个位置上的值是 quotient + (i < remainder ? 1 : 0),每一个 quotient 需要 + 1 直到把 remainder 用完为止。
复杂度
时间O(n)
空间O(1)
代码
Java实现
class Solution {
public int[] missingRolls(int[] rolls, int mean, int n) {
int m = rolls.length;
int totalSum = mean * (n + m);
int curSum = 0;
for (int roll : rolls) {
curSum += roll;
}
int restSum = totalSum - curSum;
// corner case
if (restSum < n || restSum > 6 * n) {
return new int[0];
}
// normal case
int[] res = new int[n];
int quotient = restSum / n;
int remainder = restSum % n;
for (int i = 0; i < n; i++) {
res[i] = quotient + (i < remainder ? 1 : 0);
}
return res;
}
}