LeetCode 题解工作台

使数组和能被 P 整除

给你一个正整数数组 nums ,请你移除 最短 子数组(可以为 空 ),使得剩余元素的 和 能被 p 整除。 不允许 将整个数组都移除。 请你返回你需要移除的最短子数组的长度,如果无法满足题目要求,返回 -1 。 子数组 定义为原数组中连续的一组元素。 示例 1: 输入: nums = [3,1,4…

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

我们可以先求出数组 所有元素之和模 的值,记为 。如果 为 ,说明数组 所有元素之和就是 的倍数,直接返回 即可。 如果 不为 ,我们需要找到一个最短的子数组,使得删除该子数组后,剩余元素之和模 的值为 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个正整数数组 nums,请你移除 最短 子数组(可以为 ),使得剩余元素的  能被 p 整除。 不允许 将整个数组都移除。

请你返回你需要移除的最短子数组的长度,如果无法满足题目要求,返回 -1 。

子数组 定义为原数组中连续的一组元素。

 

示例 1:

输入:nums = [3,1,4,2], p = 6
输出:1
解释:nums 中元素和为 10,不能被 p 整除。我们可以移除子数组 [4] ,剩余元素的和为 6 。

示例 2:

输入:nums = [6,3,5,2], p = 9
输出:2
解释:我们无法移除任何一个元素使得和被 9 整除,最优方案是移除子数组 [5,2] ,剩余元素为 [6,3],和为 9 。

示例 3:

输入:nums = [1,2,3], p = 3
输出:0
解释:和恰好为 6 ,已经能被 3 整除了。所以我们不需要移除任何元素。

示例  4:

输入:nums = [1,2,3], p = 7
输出:-1
解释:没有任何方案使得移除子数组后剩余元素的和被 7 整除。

示例 5:

输入:nums = [1000000000,1000000000,1000000000], p = 3
输出:0

 

提示:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109
  • 1 <= p <= 109
lightbulb

解题思路

方法一:前缀和 + 哈希表

我们可以先求出数组 nums\textit{nums} 所有元素之和模 pp 的值,记为 kk。如果 kk00,说明数组 nums\textit{nums} 所有元素之和就是 pp 的倍数,直接返回 00 即可。

如果 kk 不为 00,我们需要找到一个最短的子数组,使得删除该子数组后,剩余元素之和模 pp 的值为 00

我们可以遍历数组 nums\textit{nums},维护当前的前缀和模 pp 的值,记为 curcur。用哈希表 lastlast 记录每个前缀和模 pp 的值最后一次出现的位置。

如果当前存在一个以 nums[i]\textit{nums}[i] 结尾的子数组,使得删除该子数组后,剩余元素之和模 pp 的值为 00。也就是说,我们需要找到此前的一个前缀和模 pp 的值为 targettarget 的位置 jj,使得 (target+kcur)modp=0(target + k - cur) \bmod p = 0。如果找到,我们就可以将 j+1j + 1ii 这一段闭区间子数组 nums[j+1,..i]\textit{nums}[j+1,..i] 删除,使得剩余元素之和模 pp 的值为 00

因此,如果存在一个 target=(curk+p)modptarget = (cur - k + p) \bmod p,那么我们可以更新答案为 min(ans,ij)\min(ans, i - j)。接下来,我们更新 last[cur]last[cur] 的值为 ii。继续遍历数组 nums\textit{nums},直到遍历结束,即可得到答案。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为数组 nums\textit{nums} 的长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
    def minSubarray(self, nums: List[int], p: int) -> int:
        k = sum(nums) % p
        if k == 0:
            return 0
        last = {0: -1}
        cur = 0
        ans = len(nums)
        for i, x in enumerate(nums):
            cur = (cur + x) % p
            target = (cur - k + p) % p
            if target in last:
                ans = min(ans, i - last[target])
            last[cur] = i
        return -1 if ans == len(nums) else ans
speed

复杂度分析

指标
时间O(n)
空间O(n)
psychology

面试官常问的追问

外企场景
  • question_mark

    Do you know how to use prefix sums to avoid checking every subarray explicitly?

  • question_mark

    Can you leverage modulo arithmetic with a hash map to identify candidate subarrays efficiently?

  • question_mark

    Think about edge cases where the array sum is already divisible by p or where no subarray can satisfy the condition.

warning

常见陷阱

外企场景
  • error

    Forgetting that removing the entire array is not allowed can lead to incorrect -1 handling.

  • error

    Not using modulo operation on prefix sums can result in overflow or incorrect subarray matches.

  • error

    Failing to update the minimum subarray length correctly when multiple candidates exist can return the wrong answer.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Instead of the smallest subarray, find the largest subarray that must be removed to achieve divisibility by p.

  • arrow_right_alt

    Allow removal of multiple non-contiguous elements to make the sum divisible by p, requiring a different hashing strategy.

  • arrow_right_alt

    Solve the problem when p is not fixed but given as a list of possible divisors to test for each.

help

常见问题

外企场景

使数组和能被 P 整除题解:数组·哈希·扫描 | LeetCode #1590 中等