leetcode1814: Count the number of good pairs in an array (one question per day in 1.17)

Topic statement:

You are given an array nums containing only non-negative integers. Defines the value of rev(x) to be the result of bit-reversing the digits of the integer x. Let's say rev(123) = 321 and rev(120) = 21 . We call a subscript pair (i, j) good if it satisfies the following conditions:

0 <= i < j < nums.length
nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])
Please return the number of good subscript pairs. Since the result may be very large, please return the result modulo 109 + 7.

Example 1:

Input: nums = [42,11,1,97]
Output: 2
Explanation: The two coordinate pairs are:
 - (0,3): 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121.
 -(1,2): 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12.
Example 2:

Input: nums = [13,10,35,24,76]
Output: 4
 

hint:

1 <= nums.length <= 1e5
0 <= nums[i] <= 1e9

Problem-solving ideas:

        The question is not difficult to understand. I believe that if the length of the nums array is relatively small, it can be written directly using two for loops (violent solution), but the length of the array for this question shows that the time complexity O(N) is required.

        Through the exchange of this formula nums[i] + rev(nums[j]) == nums[j] + rev(nums[i]) can be obtained:                        nums[i] - rev(nums[i]) == nums [j] - rev(nums[ j ])

        Define a hash (unordered_map) count. When traversing the nums array, add mp【nums[i]-rev[nums[i]] every time to mod (1000000007) to take the remainder, and then mp【nums[i] ]-rev[nums[i]]+1.

Problem-solving code:

class Solution {
public:
    int countNicePairs(vector<int>& nums) {
        int cnt=0;
        unordered_map<int,int>mp;
        for(int i=0;i<nums.size();i++)
        {
            int temp=nums[i];
            int target=0;
            while(temp!=0)
            {
                int x=temp%10;
                temp=temp/10;
                target=target*10+x;
            }
            cnt=(cnt+mp[nums[i]-target])%1000000007;
            mp[nums[i]-target]++;
        }
        return cnt;
    }
};

Guess you like

Origin blog.csdn.net/m0_63743577/article/details/128720667