-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Time: O(n * (k + logU)), n: len(nums), k: 10, U: max(nums) Time of gcd: O(1) Space: O(1)
- Loading branch information
Showing
1 changed file
with
30 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
}; |