LeetCode 题解工作台

所有数对中数位差之和

你有一个数组 nums ,它只包含 正 整数,所有正整数的数位长度都 相同 。 两个整数的 数位差 指的是两个整数 相同 位置上不同数字的数目。 请你返回 nums 中 所有 整数对里, 数位差之和。 示例 1: 输入: nums = [13,23,12] 输出: 4 解释: 计算过程如下: - 1…

category

4

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

我们先获取数组中数字的位数 ,然后对于每一位,我们统计数组 中每个数字在该位上的出现次数,记为 。那么在该位上,所有数对的数位不同之和为: $$

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

你有一个数组 nums ,它只包含  整数,所有正整数的数位长度都 相同 。

两个整数的 数位差 指的是两个整数 相同 位置上不同数字的数目。

请你返回 nums 中 所有 整数对里,数位差之和。

 

示例 1:

输入:nums = [13,23,12]

输出:4

解释:
计算过程如下:
13 和 23 的数位差为 1 。
- 13 和 12 的数位差为 1 。
23 和 12 的数位差为 2 。
所以所有整数数对的数位差之和为 1 + 1 + 2 = 4 。

示例 2:

输入:nums = [10,10,10,10]

输出:0

解释:
数组中所有整数都相同,所以所有整数数对的数位不同之和为 0 。

 

提示:

  • 2 <= nums.length <= 105
  • 1 <= nums[i] < 109
  • nums 中的整数都有相同的数位长度。
lightbulb

解题思路

方法一:计数

我们先获取数组中数字的位数 mm,然后对于每一位,我们统计数组 nums\textit{nums} 中每个数字在该位上的出现次数,记为 cnt\textit{cnt}。那么在该位上,所有数对的数位不同之和为:

vcntv×(nv)\sum_{v \in \textit{cnt}} v \times (n - v)

其中 nn 是数组的长度。我们将所有位的数位不同之和相加,再除以 22 即可得到答案。

时间复杂度 O(n×m)O(n \times m),空间复杂度 O(C)O(C),其中 nnmm 分别是数组的长度和数字的位数;而 CC 是常数,本题中 C=10C = 10

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
    def sumDigitDifferences(self, nums: List[int]) -> int:
        n = len(nums)
        m = int(log10(nums[0])) + 1
        ans = 0
        for _ in range(m):
            cnt = Counter()
            for i, x in enumerate(nums):
                nums[i], y = divmod(x, 10)
                cnt[y] += 1
            ans += sum(v * (n - v) for v in cnt.values()) // 2
        return ans
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Look for an understanding of how to optimize comparing digits by position.

  • question_mark

    Evaluate the candidate's ability to reduce a complex problem into smaller sub-tasks.

  • question_mark

    Check if the candidate correctly utilizes hash tables to reduce time complexity.

warning

常见陷阱

外企场景
  • error

    Candidates may try to compare each pair of integers directly, leading to a brute-force solution with poor time complexity.

  • error

    Forgetting to optimize digit position comparisons could result in inefficient solutions.

  • error

    Not summing up the results correctly across all digit positions could lead to an incorrect final answer.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the integers have varying numbers of digits?

  • arrow_right_alt

    What if the array contains non-positive integers?

  • arrow_right_alt

    Can the problem be optimized for space instead of time complexity?

help

常见问题

外企场景

所有数对中数位差之和题解:数组·哈希·扫描 | LeetCode #3153 中等