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

给你一个数组 nums ,数组中只包含非负整数。定义 rev(x) 的值为将整数 x 各个数字位反转得到的结果。比方说 rev(123) = 321 , rev(120) = 21 。我们称满足下面条件的下标对 (i, j) 是 好的 :

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

请你返回好下标对的数目。由于结果可能会很大,请将结果对 109 + 7 取余 后返回。

 

示例 1:

输入:nums = [42,11,1,97]
输出:2
解释:两个坐标对为:
 - (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 。

示例 2:

输入:nums = [13,10,35,24,76]
输出:4

 

提示:

  • 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  阅读(74)  评论(0编辑  收藏  举报