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
题目链接:https://leetcode.com/problems/count-nice-pairs-in-an-array/
题目大意:给一个数组,求满足题目条件公式的数对个数
题目分析:遇到nums[i]+rev(nums[j])==nums[j]+rev(nums[i])这种i和j分别在等式两边的问题首先要考虑将相同的变量放到一边(记得有一题条件是求nums[j]-nums[i]==j-i的对数,本质上和此题一样),于是有nums[j]-rev(nums[j])== nums[i]-rev(nums[i]),哈希一下即可
这道题我另外一个思路过不了倒数第二组数据,通过二分测试集找到了问题所在,以及一个有趣结论,感兴趣的可以参考下面的链接:
https://leetcode.com/problems/count-nice-pairs-in-an-array/discuss/1757293
57ms,时间击败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;
}
}