From dec54e2b27df7cbdba48b7c51a923ddae70bc3a0 Mon Sep 17 00:00:00 2001 From: aucker Date: Thu, 20 Jun 2024 23:02:18 +0800 Subject: [PATCH] June20: nums of beautiful pairs [M] Time: O(n * (k + logU)), n: len(nums), k: 10, U: max(nums) Time of gcd: O(1) Space: O(1) --- daily/June20.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 daily/June20.cpp diff --git a/daily/June20.cpp b/daily/June20.cpp new file mode 100644 index 0000000..85f2e44 --- /dev/null +++ b/daily/June20.cpp @@ -0,0 +1,30 @@ +#include +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& 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; + } +}; \ No newline at end of file