2748. 美丽下标对的数目
题目描述
给你一个下标从 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
解法
方法一:计数
我们可以用一个长度为 $10$ 的数组 $\textit{cnt}$ 来记录每个数字的第一个数字出现的次数。
遍历数组 $\textit{nums}$,对于每个数字 $x$,我们枚举 $0$ 到 $9$ 的每个数字 $y$,如果 $\textit{cnt}[y]$ 不为 $0$ 且 $\textit{gcd}(x b\mod 10, y) = 1$,则答案加上 $\textit{cnt}[y]$。然后,我们将 $x$ 的第一个数字出现的次数加 $1$。
遍历结束后,返回答案即可。
时间复杂度 $O(n \times (k + \log M))$,空间复杂度 $O(k + \log M)$。其中 $n$ 为数组 $\textit{nums}$ 的长度,而 $k$ 和 $M$ 分别表示数组 $\textit{nums}$ 中的数字的种类以及最大值。
Python3
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
Java
class Solution {
public int countBeautifulPairs(int[] nums) {
int[] cnt = new int[10];
int ans = 0;
for (int x : nums) {
for (int y = 0; y < 10; ++y) {
if (cnt[y] > 0 && gcd(x % 10, y) == 1) {
ans += cnt[y];
}
}
while (x > 9) {
x /= 10;
}
++cnt[x];
}
return ans;
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
C++
class Solution {
public:
int countBeautifulPairs(vector<int>& nums) {
int cnt[10]{};
int ans = 0;
for (int x : nums) {
for (int y = 0; y < 10; ++y) {
if (cnt[y] && gcd(x % 10, y) == 1) {
ans += cnt[y];
}
}
while (x > 9) {
x /= 10;
}
++cnt[x];
}
return ans;
}
};
Go
func countBeautifulPairs(nums []int) (ans int) {
cnt := [10]int{}
for _, x := range nums {
for y := 0; y < 10; y++ {
if cnt[y] > 0 && gcd(x%10, y) == 1 {
ans += cnt[y]
}
}
for x > 9 {
x /= 10
}
cnt[x]++
}
return
}
func gcd(a, b int) int {
if b == 0 {
return a
}
return gcd(b, a%b)
}
TypeScript
function countBeautifulPairs(nums: number[]): number {
const cnt: number[] = Array(10).fill(0);
let ans = 0;
for (let x of nums) {
for (let y = 0; y < 10; ++y) {
if (cnt[y] > 0 && gcd(x % 10, y) === 1) {
ans += cnt[y];
}
}
while (x > 9) {
x = Math.floor(x / 10);
}
++cnt[x];
}
return ans;
}
function gcd(a: number, b: number): number {
if (b === 0) {
return a;
}
return gcd(b, a % b);
}