LeetCode 题解工作台
使数组和能被 K 整除的最少操作次数
给你一个整数数组 nums 和一个整数 k 。你可以执行以下操作任意次: 选择一个下标 i ,并将 nums[i] 替换为 nums[i] - 1 。 返回使数组元素之和能被 k 整除所需的 最小 操作次数。 示例 1: 输入: nums = [3,9,7], k = 5 输出: 4 解释: 对 n…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·数学
答案摘要
题目实际上是求数组元素之和对 取模的结果。因此,我们只需要遍历数组,计算出所有元素之和,然后对 取模,最后返回这个结果即可。 时间复杂度 ,其中 是数组 的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个整数数组 nums 和一个整数 k。你可以执行以下操作任意次:
- 选择一个下标
i,并将nums[i]替换为nums[i] - 1。
返回使数组元素之和能被 k 整除所需的最小操作次数。
示例 1:
输入: nums = [3,9,7], k = 5
输出: 4
解释:
- 对
nums[1] = 9执行 4 次操作。现在nums = [3, 5, 7]。 - 数组之和为 15,可以被 5 整除。
示例 2:
输入: nums = [4,1,3], k = 4
输出: 0
解释:
- 数组之和为 8,已经可以被 4 整除。因此不需要操作。
示例 3:
输入: nums = [3,2], k = 6
输出: 5
解释:
- 对
nums[0] = 3执行 3 次操作,对nums[1] = 2执行 2 次操作。现在nums = [0, 0]。 - 数组之和为 0,可以被 6 整除。
提示:
1 <= nums.length <= 10001 <= nums[i] <= 10001 <= k <= 100
解题思路
方法一:求和取模
题目实际上是求数组元素之和对 取模的结果。因此,我们只需要遍历数组,计算出所有元素之和,然后对 取模,最后返回这个结果即可。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
return sum(nums) % k
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Tests understanding of modulo and array manipulation.
- question_mark
Evaluates ability to work with array sums and math-based optimizations.
- question_mark
Assesses problem-solving skills in handling operations within constraints.
常见陷阱
外企场景- error
Forgetting to account for the case where the sum is already divisible by k (requires zero operations).
- error
Overcomplicating the problem by trying to use more than one operation per element.
- error
Not correctly adjusting the sum by the minimum necessary amount, leading to incorrect results.
进阶变体
外企场景- arrow_right_alt
What if we allowed negative numbers in the array?
- arrow_right_alt
What if the array elements were limited to powers of two?
- arrow_right_alt
What if we needed to make the sum divisible by a prime number instead of k?