# 5708. 统计一个数组中好对子的数目

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

输入：nums = [42,11,1,97]

- (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 。


输入：nums = [13,10,35,24,76]



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

nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])=>

(nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j]))=>

Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values.=>

add  c*(c-1)/2  to the ans for each c in the Counter()

python

class Solution:
def countNicePairs(self, nums: List[int]) -> int:
for i in range(len(nums)):
nums[i]=nums[i]-int(str(nums[i])[::-1])
cnt=collections.Counter(nums)
ans=0
for c in cnt.values():
ans+=(c*(c-1)/2)
return int(ans)%(10**9+7)

C++

class Solution {
public:
int countNicePairs(vector<int>& nums) {
long ans=0;
unordered_map<int,int> m;
for(int n:nums){
string s=to_string(n);
reverse(s.begin(),s.end());
ans+=(m[n-stoi(s)])++;
}
return ans%(long)(1e9+7);
}
};

posted @ 2021-04-04 10:13  XXXSANS  阅读(63)  评论(0编辑  收藏  举报