LeetCode 题解工作台
所有数对中数位差之和
你有一个数组 nums ,它只包含 正 整数,所有正整数的数位长度都 相同 。 两个整数的 数位差 指的是两个整数 相同 位置上不同数字的数目。 请你返回 nums 中 所有 整数对里, 数位差之和。 示例 1: 输入: nums = [13,23,12] 输出: 4 解释: 计算过程如下: - 1…
4
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们先获取数组中数字的位数 ,然后对于每一位,我们统计数组 中每个数字在该位上的出现次数,记为 。那么在该位上,所有数对的数位不同之和为: $$
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
你有一个数组 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 <= 1051 <= nums[i] < 109nums中的整数都有相同的数位长度。
解题思路
方法一:计数
我们先获取数组中数字的位数 ,然后对于每一位,我们统计数组 中每个数字在该位上的出现次数,记为 。那么在该位上,所有数对的数位不同之和为:
其中 是数组的长度。我们将所有位的数位不同之和相加,再除以 即可得到答案。
时间复杂度 ,空间复杂度 ,其中 和 分别是数组的长度和数字的位数;而 是常数,本题中 。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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?