-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 1814. Count Nice Pairs in an Array (#349)
- Loading branch information
Showing
1 changed file
with
27 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,27 @@ | ||
class Solution { | ||
public: | ||
// time/space: O(nlogk)/O(n) | ||
int countNicePairs(vector<int>& nums) { | ||
// count the difference for each number with its reverse | ||
unordered_map<int, int> hash; | ||
for (auto& num : nums) hash[num - rev(num)]++; | ||
|
||
// count the nice pairs | ||
int count = 0; | ||
for (auto& [key, value] : hash) { | ||
long long pairs = ((1LL * value * (value - 1)) / 2LL) % MOD; | ||
count = (count + pairs) % MOD; | ||
} | ||
return count; | ||
} | ||
private: | ||
const int MOD = 1e9 + 7; | ||
int rev(int x) { | ||
int result = 0; | ||
while (x > 0) { | ||
result = 10 * result + (x % 10); | ||
x /= 10; | ||
} | ||
return result; | ||
} | ||
}; |