给你一个下标从 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 <= 100
1 <= nums[i] <= 9999
nums[i] % 10 != 0
提示 1
Since nums.length is small, you can find all pairs of indices and check if each pair is beautiful.
提示 2
Use integer to string conversion to get the first and last digit of each number.
解法:哈希表
公因数只有1的两个非零自然数,叫做互质数。
用一个数组 count[i] 来表示第一个数字为 i 的元素个数。
遍历数组,求出元素的最后一个数字,再枚举 1 到 9, 根据对应 count[i] 计算美丽下标对个数。同时再求出元素的第一个数字,来更新 count[]。
最后返回结果即可。
用辗转相除法 最后返回的最大公因数 是否为 1,判断两个数是否为互质数。
Java版:
class Solution {
public int countBeautifulPairs(int[] nums) {
int ans = 0;
int n = nums.length;
// 记录 首位数字为 1~9 的个数
int[] count = new int[10];
for (int num: nums) {
for (int i = 1; i <= 9; i++) {
if (gcd(num % 10, i) == 1) {
ans += count[i];
}
}
while (num >= 10) {
num /= 10;
}
count[num]++;
}
return ans;
}
private int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
}
Python3版:
class Solution:
def countBeautifulPairs(self, nums: List[int]) -> int:
ans = 0
count = [0] * 10
for num in nums:
for i in range(1, 10):
if gcd(num % 10, i) == 1:
ans += count[i]
while num >= 10:
num //= 10
count[num] += 1
return ans
复杂度分析
- 时间复杂度:O(n×(9+logC)),其中 n 是数组的长度,C 是 nums[i] 的最大值。
- 空间复杂度:O(1)。