Description Link to heading

1814.count-nice-pairs-in-an-array

Solution Link to heading

We can change the requirements to nums[i] - rev(nums[i]) == nums[j] - rev(nums[j]).

Then we use hash tables to record the times of occurrence of the value.

Code Link to heading

class Solution {
public:
    int rev(int num)  {
        vector<int> tmp;
        int ans = 0;
        while (num != 0) {
            tmp.push_back(num % 10);
            num /= 10;
        }
        for (int i = 0; i < tmp.size(); i++) {
            ans = ans * 10 + tmp[i];
        }
        return ans;
    }
    int countNicePairs(vector<int>& nums) {
        map<int, int> mp;
        for (int i = 0; i < nums.size(); i++) {
            mp[nums[i] - rev(nums[i])]++;
        }
        long long ans = 0;
        for (auto it = mp.begin(); it != mp.end(); it++) {
            ans += (long long) it->second * (it->second - 1) / 2;
        }
        return ans % (1000000007);
    }
};