连续子数组零尾数问题 |豆包MarsCode AI刷题

64 阅读2分钟

解题思路

  1. 理解问题

    • 我们需要计算数组中连续子数组的数量,这些子数组的乘积末尾零的数量大于等于 x
    • 末尾零的数量取决于乘积中因子 2 和 5 的数量,因为 10 = 2 * 5
  2. 数据结构选择

    • 我们可以使用两个数组来分别记录从左到右的累积因子 2 和 5 的数量。
  3. 算法步骤

    • 遍历数组,计算每个元素的因子 2 和 5 的数量。
    • 使用前缀和数组记录从左到右的累积因子 2 和 5 的数量。
    • 使用双指针或滑动窗口来计算满足条件的子数组数量。
public class Main {
    public static int solution(int[] a, int x) {
        // 计算每个元素的因子2和5的数量
        int[] count2 = new int[a.length];
        int[] count5 = new int[a.length];
        for (int i = 0; i < a.length; i++) {
            count2[i] = countFactors(a[i], 2);
            count5[i] = countFactors(a[i], 5);
        }

        // 计算前缀和
        int[] prefix2 = new int[a.length + 1];
        int[] prefix5 = new int[a.length + 1];
        for (int i = 1; i <= a.length; i++) {
            prefix2[i] = prefix2[i - 1] + count2[i - 1];
            prefix5[i] = prefix5[i - 1] + count5[i - 1];
        }

        // 计算满足条件的子数组数量
        int result = 0;
        for (int i = 0; i < a.length; i++) {
            for (int j = i; j < a.length; j++) {
                int total2 = prefix2[j + 1] - prefix2[i];
                int total5 = prefix5[j + 1] - prefix5[i];
                if (Math.min(total2, total5) >= x) {
                    result++;
                }
            }
        }

        return result % 1000000007;
    }

    // 计算一个数的因子数量
    private static int countFactors(int num, int factor) {
        int count = 0;
        while (num % factor == 0) {
            num /= factor;
            count++;
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(solution(new int[]{5, 2, 3, 50, 4}, 2) == 6);
        System.out.println(solution(new int[]{10, 5, 2, 1}, 3) == 0);
        System.out.println(solution(new int[]{25, 4, 8}, 1) == 2);
    }
}


### 关键步骤解释

1.  **计算因子数量**:

    -   `countFactors` 函数用于计算一个数中某个因子的数量。

1.  **前缀和数组**:

    -   `prefix2` 和 `prefix5` 数组用于记录从左到右的累积因子 `2` 和 `5` 的数量。

1.  **双层循环**:

    -   使用双层循环遍历所有可能的子数组,并计算每个子数组的因子 `2` 和 `5` 的数量。
    -   如果某个子数组的因子 `2` 和 `5` 的最小值大于等于 `x`,则计入结果。

### 提示

-   你可以先实现 `countFactors` 函数,然后逐步实现前缀和数组和双层循环部分。
-   注意在计算结果时对 `10^9 + 7` 取模。

通过这些步骤,你可以逐步实现代码,解决这个问题。希望这些提示对你有帮助!如果你有任何问题或需要进一步的帮助,请告诉我。