LeetCode 题解工作台
美丽下标对的数目
给你一个下标从 0 开始的整数数组 nums 。如果下标对 i 、 j 满足 0 ≤ i ,如果 nums[i] 的 第一个数字 和 nums[j] 的 最后一个数字 互质 ,则认为 nums[i] 和 nums[j] 是一组 美丽下标对 。 返回 nums 中 美丽下标对 的总数目。 对于两个整数…
5
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们可以用一个长度为 的数组 来记录每个数字的第一个数字出现的次数。 遍历数组 ,对于每个数字 ,我们枚举 到 的每个数字 ,如果 不为 且 $\textit{gcd}(x b\mod 10, y) = 1$,则答案加上 。然后,我们将 的第一个数字出现的次数加 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums 。如果下标对 i、j 满足 0 ≤ i < j < nums.length ,如果 nums[i] 的 第一个数字 和 nums[j] 的 最后一个数字 互质 ,则认为 nums[i] 和 nums[j] 是一组 美丽下标对 。
返回 nums 中 美丽下标对 的总数目。
对于两个整数 x 和 y ,如果不存在大于 1 的整数可以整除它们,则认为 x 和 y 互质 。换而言之,如果 gcd(x, y) == 1 ,则认为 x 和 y 互质,其中 gcd(x, y) 是 x 和 y 的 最大公因数 。
示例 1:
输入:nums = [2,5,1,4] 输出:5 解释:nums 中共有 5 组美丽下标对: i = 0 和 j = 1 :nums[0] 的第一个数字是 2 ,nums[1] 的最后一个数字是 5 。2 和 5 互质,因此 gcd(2,5) == 1 。 i = 0 和 j = 2 :nums[0] 的第一个数字是 2 ,nums[2] 的最后一个数字是 1 。2 和 1 互质,因此 gcd(2,1) == 1 。 i = 1 和 j = 2 :nums[1] 的第一个数字是 5 ,nums[2] 的最后一个数字是 1 。5 和 1 互质,因此 gcd(5,1) == 1 。 i = 1 和 j = 3 :nums[1] 的第一个数字是 5 ,nums[3] 的最后一个数字是 4 。5 和 4 互质,因此 gcd(5,4) == 1 。 i = 2 和 j = 3 :nums[2] 的第一个数字是 1 ,nums[3] 的最后一个数字是 4 。1 和 4 互质,因此 gcd(1,4) == 1 。 因此,返回 5 。
示例 2:
输入:nums = [11,21,12] 输出:2 解释:共有 2 组美丽下标对: i = 0 和 j = 1 :nums[0] 的第一个数字是 1 ,nums[1] 的最后一个数字是 1 。gcd(1,1) == 1 。 i = 0 和 j = 2 :nums[0] 的第一个数字是 1 ,nums[2] 的最后一个数字是 2 。gcd(1,2) == 1 。 因此,返回 2 。
提示:
2 <= nums.length <= 1001 <= nums[i] <= 9999nums[i] % 10 != 0
解题思路
方法一:计数
我们可以用一个长度为 的数组 来记录每个数字的第一个数字出现的次数。
遍历数组 ,对于每个数字 ,我们枚举 到 的每个数字 ,如果 不为 且 ,则答案加上 。然后,我们将 的第一个数字出现的次数加 。
遍历结束后,返回答案即可。
时间复杂度 ,空间复杂度 。其中 为数组 的长度,而 和 分别表示数组 中的数字的种类以及最大值。
class Solution:
def countBeautifulPairs(self, nums: List[int]) -> int:
cnt = [0] * 10
ans = 0
for x in nums:
for y in range(10):
if cnt[y] and gcd(x % 10, y) == 1:
ans += cnt[y]
cnt[int(str(x)[0])] += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity ranges from O(n^2) for naive pair checking to O(n) if using hash table with precomputed coprime relationships. Space complexity is O(10) for the digit frequency hash and coprime table. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expecting you to notice nums.length is small and brute-force is feasible but can be optimized.
- question_mark
Looking for awareness of coprime checking and avoiding repeated gcd calculations.
- question_mark
Interested in using array scanning combined with hash lookup to efficiently count pairs.
常见陷阱
外企场景- error
Forgetting that only the first digit of nums[i] and last digit of nums[j] matter.
- error
Checking gcd for all pairs without using a hash leads to unnecessary repeated calculations.
- error
Mistakenly including pairs where i >= j or last digits are zero.
进阶变体
外企场景- arrow_right_alt
Count beautiful pairs where first and last digits are multiples instead of coprime.
- arrow_right_alt
Consider arrays with zeros and handle last digit extraction carefully.
- arrow_right_alt
Extend to larger numbers or larger digit ranges requiring different hashing strategies.