1814.统计一个数组中好对子的数目
链接:1814.统计一个数组中好对子的数目
难度:Medium
标签:数组、哈希表、数学、计数
简介:请你返回好下标对的数目。
题解 1 - cpp
- 编辑时间:2023-01-17
- 执行用时:84ms
- 内存消耗:55.5MB
- 编程语言:cpp
- 解法介绍:双指针递归。
const int mod = 1e9 + 7;
class Solution {
public:
    int countNicePairs(vector<int>& nums) {
        unordered_map<int, int> m;
        int ans = 0;
        for (auto &num : nums) ans = (ans + m[num - rev(num)]++) % mod;
        return ans;
    }
    int rev(int num) {
        int ans = 0;
        for (; num; num /= 10) ans = ans * 10 + num % 10;
        return ans;
    }
};
题解 2 - rust
- 编辑时间:2023-01-17
- 执行用时:24ms
- 内存消耗:3.7MB
- 编程语言:rust
- 解法介绍:同上。
use std::collections::HashMap;
const MOD: i32 = 1000000007;
impl Solution {
    pub fn count_nice_pairs(nums: Vec<i32>) -> i32 {
        let mut m = HashMap::<i32, i32>::new();
        let mut ans = 0;
        for num in nums {
            let k = num - Solution::rev(num);
            let v = if m.contains_key(&k) {
                m.get_mut(&k).unwrap()
            } else {
                m.insert(k, 0);
                m.get_mut(&k).unwrap()
            };
            ans = (ans + *v) % MOD;
            *v += 1;
        }
        ans
    }
    fn rev(num: i32) -> i32 {
        let mut num = num;
        let mut ans = 0;
        while num != 0 {
            ans = ans * 10 + num % 10;
            num /= 10;
        }
        ans
    }
}
题解 3 - python
- 编辑时间:2023-01-17
- 执行用时:260ms
- 内存消耗:23.1MB
- 编程语言:python
- 解法介绍:双指针递归。
class Solution:
def countNicePairs(self, nums: List[int]) -> int:
    m = Counter()
    ans = 0
    for num in nums:
        k = num - int(str(num)[::-1])
        ans += m[k]
        m[k] += 1
    return int(ans % (1e9 + 7))