LeetCode 1814 Count Nice Pairs in an Array (map 推荐)

这篇博客主要探讨了LeetCode上的一个问题,即计算数组中满足`nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])`条件的数对数量。博主分享了一种解决方案,通过哈希表存储差值并更新计数,从而有效地解决了问题。此外,还提到了在实现过程中遇到的问题以及通过二分查找找到的错误原因。该博客适合对算法和哈希表有兴趣的读者阅读。
摘要由CSDN通过智能技术生成

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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值