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;
}
}