LeetCode 题解工作台
数组元素和与数字和的绝对差
给你一个正整数数组 nums 。 元素和 是 nums 中的所有元素相加求和。 数字和 是 nums 中每一个元素的每一数位(重复数位需多次求和)相加求和。 返回 元素和 与 数字和 的绝对差。 注意: 两个整数 x 和 y 的绝对差定义为 |x - y| 。 示例 1: 输入: nums = [1…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·数学
答案摘要
我们遍历数组 ,计算元素和 和数字和 ,最后返回 $|x - y|$ 即可。由于 一定大于等于 ,所以我们也可以直接返回 $x - y$。 时间复杂度 $O(n \times \log_{10} M)$,其中 和 分别是数组 的长度和数组中元素的最大值。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个正整数数组 nums 。
- 元素和 是
nums中的所有元素相加求和。 - 数字和 是
nums中每一个元素的每一数位(重复数位需多次求和)相加求和。
返回 元素和 与 数字和 的绝对差。
注意:两个整数 x 和 y 的绝对差定义为 |x - y| 。
示例 1:
输入:nums = [1,15,6,3] 输出:9 解释: nums 的元素和是 1 + 15 + 6 + 3 = 25 。 nums 的数字和是 1 + 1 + 5 + 6 + 3 = 16 。 元素和与数字和的绝对差是 |25 - 16| = 9 。
示例 2:
输入:nums = [1,2,3,4] 输出:0 解释: nums 的元素和是 1 + 2 + 3 + 4 = 10 。 nums 的数字和是 1 + 2 + 3 + 4 = 10 。 元素和与数字和的绝对差是 |10 - 10| = 0 。
提示:
1 <= nums.length <= 20001 <= nums[i] <= 2000
解题思路
方法一:模拟
我们遍历数组 ,计算元素和 和数字和 ,最后返回 即可。由于 一定大于等于 ,所以我们也可以直接返回 。
时间复杂度 ,其中 和 分别是数组 的长度和数组中元素的最大值。空间复杂度 。
class Solution:
def differenceOfSum(self, nums: List[int]) -> int:
x = y = 0
for v in nums:
x += v
while v:
y += v % 10
v //= 10
return x - y
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Tests ability to loop through an array efficiently.
- question_mark
Checks understanding of digit extraction from integers.
- question_mark
Evaluates correctness in calculating absolute differences.
常见陷阱
外企场景- error
Forgetting to correctly sum the digits of numbers with multiple digits.
- error
Not taking the absolute value of the difference between sums.
- error
Incorrectly handling large numbers or edge cases with single-digit arrays.
进阶变体
外企场景- arrow_right_alt
Change the array to contain only single-digit numbers.
- arrow_right_alt
Increase the array size to test scalability.
- arrow_right_alt
Introduce negative integers to test how absolute values are handled.