2028. 找出缺失的观测数据

73 阅读2分钟

题目

现有一份 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 整除。

思路

暴力解法.. 还是太菜了想不到别的方法...

求出总数后减去已知的数量得出未知的数量 total

枚举选1-6的情况,

如果剩余数量*(1-6)>=剩余总数 total 且 剩余数量*(1-6)-1 < total 则 ans[i] = (1-6)

代码

class Solution {
    public int[] missingRolls(int[] rolls, int mean, int n) {
        int[] ans = new int[n];
        int m = rolls.length;
        int total = (n + m) * mean;
        for (int roll : rolls) {
            total -= roll;
        }
        if (n * 6 < total) {
            return new int[0];
        }
        int index = n;
        for (int i = 0; i < n; i++) {
            if (index * 6 >= total && index * 5 < total) {
                ans[i] = 6;
                total -= ans[i];
            } else if (index * 5 >= total && index * 4 < total) {
                ans[i] = 5;
                total -= ans[i];
            } else if (index * 4 >= total && index * 3 < total) {
                ans[i] = 4;
                total -= ans[i];
            } else if (index * 3 >= total && index * 2 < total) {
                ans[i] = 3;
                total -= ans[i];
            } else if (index * 2 >= total && index < total) {
                ans[i] = 2;
                total -= ans[i];
            } else if (index == total) {
                ans[i] = 1;
                total -= ans[i];
            }else{
                return new int[0];
            }
            index--;
        }
        return ans;
    }
}

题解

三叶姐题解: leetcode.cn/problems/fi…