Skip to content

Commit

Permalink
June20: nums of beautiful pairs [M]
Browse files Browse the repository at this point in the history
Time: O(n * (k + logU)), n: len(nums), k: 10, U: max(nums)
Time of gcd: O(1)
Space: O(1)
  • Loading branch information
aucker committed Jun 20, 2024
1 parent d544d7a commit dec54e2
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions daily/June20.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
/**
* @brief LC: 2748: Number of Beautiful Pairs [M]
* Time: O(n*(k + logU)), n: len(nums), k = 10, U=max(nums)
* Time complexity of gcd is O(1)
* Space: O(k)
*
* @param nums
* @return int
*/
int countBeautifulPairs(vector<int>& nums) {
int ans = 0, cnt[10]{};
for (int x : nums) {
for (int y = 1; y < 10; y++) {
if (cnt[y] && gcd(y, x % 10) == 1) {
ans += cnt[y];
}
}
while (x >= 10) {
x /= 10;
}
cnt[x]++; // count times of highest
}
return ans;
}
};

0 comments on commit dec54e2

Please sign in to comment.