LeetCode 题解工作台

数组元素和与数字和的绝对差

给你一个正整数数组 nums 。 元素和 是 nums 中的所有元素相加求和。 数字和 是 nums 中每一个元素的每一数位(重复数位需多次求和)相加求和。 返回 元素和 与 数字和 的绝对差。 注意: 两个整数 x 和 y 的绝对差定义为 |x - y| 。 示例 1: 输入: nums = [1…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·数学

bolt

答案摘要

我们遍历数组 ,计算元素和 和数字和 ,最后返回 $|x - y|$ 即可。由于 一定大于等于 ,所以我们也可以直接返回 $x - y$。 时间复杂度 $O(n \times \log_{10} M)$,其中 和 分别是数组 的长度和数组中元素的最大值。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个正整数数组 nums

  • 元素和nums 中的所有元素相加求和。
  • 数字和 是 nums 中每一个元素的每一数位(重复数位需多次求和)相加求和。

返回 元素和数字和 的绝对差。

注意:两个整数 xy 的绝对差定义为 |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 <= 2000
  • 1 <= nums[i] <= 2000
lightbulb

解题思路

方法一:模拟

我们遍历数组 nums\textit{nums},计算元素和 xx 和数字和 yy,最后返回 xy|x - y| 即可。由于 xx 一定大于等于 yy,所以我们也可以直接返回 xyx - y

时间复杂度 O(n×log10M)O(n \times \log_{10} M),其中 nnMM 分别是数组 nums\textit{nums} 的长度和数组中元素的最大值。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

数组元素和与数字和的绝对差题解:数组·数学 | LeetCode #2535 简单