当前位置:网站首页>Leetcode 1814 count nice pairs in an array (recommended by map)

Leetcode 1814 count nice pairs in an array (recommended by map)

2022-06-11 01:39:00 _ TCgogogo_

You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x. For example, rev(123) = 321, and rev(120) = 21. A pair of indices (i, j) is nice if it satisfies all of the following conditions:

  • 0 <= i < j < nums.length
  • nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])

Return the number of nice pairs of indices. Since that number can be too large, return it modulo 109 + 7.

Example 1:

Input: nums = [42,11,1,97]
Output: 2
Explanation: The two 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

Constraints:

  • 1 <= nums.length <= 105
  • 0 <= nums[i] <= 109

Topic link :https://leetcode.com/problems/count-nice-pairs-in-an-array/

The main idea of the topic : Give an array , Find the number of pairs of formulas that meet the conditions of the topic

Topic analysis : encounter nums[i]+rev(nums[j])==nums[j]+rev(nums[i]) such i and j For problems on both sides of the equation, first consider putting the same variables aside ( I remember that there is a problem that the condition is to find nums[j]-nums[i]==j-i The logarithmic , It is essentially the same as this question ), So there is nums[j]-rev(nums[j])== nums[i]-rev(nums[i]), Hash it

I can't pass the penultimate set of data in another way , The problem is found through the binary test set , And an interesting conclusion , Interested parties can refer to the following links :

https://leetcode.com/problems/count-nice-pairs-in-an-array/discuss/1757293

57ms, Time beats 60%

class Solution {

    public int countNicePairs(int[] nums) {
        Map<Integer, Integer> mp = new HashMap<>();
        int ans = 0;
        for (int num : nums) {
            int key = num - calRev(num);
            int val = mp.getOrDefault(key, 0);
            ans = (ans + val) % 1000000007;
            mp.put(key, val + 1);
        }

        return ans;
    }

    private int calRev(int x) {
        int ans = 0;
        while (x > 0) {
            ans = ans * 10 + x % 10;
            x /= 10;
        }
        return ans;
    }
}

原网站

版权声明
本文为[_ TCgogogo_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020623425616.html

随机推荐