LeetCode 题解工作台
使所有元素都可以被 3 整除的最少操作数
给你一个整数数组 nums 。一次操作中,你可以将 nums 中的 任意 一个元素增加或者减少 1 。 请你返回将 nums 中所有元素都可以被 3 整除的 最少 操作次数。 示例 1: 输入: nums = [1,2,3,4] 输出: 3 解释: 通过以下 3 个操作,数组中的所有元素都可以被 3…
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·数学
答案摘要
我们直接遍历数组 ,对于每个元素 ,如果 $x \bmod 3 \neq 0$,那么有两种情况: - 如果 $x \bmod 3 = 1$,我们可以将 减少 ,使其变为 $x - 1$,此时 $x - 1$ 可以被 整除。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个整数数组 nums 。一次操作中,你可以将 nums 中的 任意 一个元素增加或者减少 1 。
请你返回将 nums 中所有元素都可以被 3 整除的 最少 操作次数。
示例 1:
输入:nums = [1,2,3,4]
输出:3
解释:
通过以下 3 个操作,数组中的所有元素都可以被 3 整除:
- 将 1 减少 1 。
- 将 2 增加 1 。
- 将 4 减少 1 。
示例 2:
输入:nums = [3,6,9]
输出:0
提示:
1 <= nums.length <= 501 <= nums[i] <= 50
解题思路
方法一:计数
我们直接遍历数组 ,对于每个元素 ,如果 ,那么有两种情况:
- 如果 ,我们可以将 减少 ,使其变为 ,此时 可以被 整除。
- 如果 ,我们可以将 增加 ,使其变为 ,此时 可以被 整除。
因此,我们只需要统计数组中不能被 整除的元素个数,即可得到最少操作次数。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
class Solution:
def minimumOperations(self, nums: List[int]) -> int:
return sum(x % 3 != 0 for x in nums)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for the candidate's ability to recognize the mod 3 pattern and simplify operations efficiently.
- question_mark
Assess how quickly the candidate arrives at an optimal approach without brute force.
- question_mark
Evaluate the candidate's approach to handling edge cases, such as when all elements are divisible by 3.
常见陷阱
外企场景- error
Failing to correctly handle numbers that are already divisible by 3, leading to unnecessary operations.
- error
Overcomplicating the approach by not recognizing the simple modulo operation as the key to reducing the problem.
- error
Missing the importance of minimizing operations, focusing too much on iteration rather than arithmetic steps.
进阶变体
外企场景- arrow_right_alt
What if the array contains only zeros?
- arrow_right_alt
How would the solution change if elements could be multiplied or divided instead of added/subtracted?
- arrow_right_alt
What happens if the array contains negative numbers?