[LeetCode] 1814. Count Nice Pairs in an Array
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 <= 10^5
0 <= nums[i] <= 10^9
统计一个数组中好对子的数目。
给你一个数组 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 取余 后返回。来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/count-nice-pairs-in-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
这道题思路类似 two sum。注意题目描述,题目让你找的是有多少对下标(i, j)满足 nums[i] + rev(nums[j]) == nums[j] + rev(nums[i]),其中 rev() 函数是把这个数字翻转过来。
这个题目很像 two sum,也是找两数之和。注意题目给出的数据范围,0 <= nums[i] <= 10^9
,所以我们反转一个数字nums[i]
的时候,很可能反转的结果rev(nums[i])
就超出整形的边界了。要想个办法规避这个问题。
这里我们可以把这个等式转换成 nums[i] - rev(nums[i]) == nums[j] - rev(nums[j]),这样我们找的就是是否存在两个不同的下标,对应的两个数字的 nums[i] - rev(nums[i]) 相等。这里为了保险起见,计算结果我用了 long 型避免溢出。
复杂度
时间O(n * logC) - rev()函数的复杂度是 logC
空间O(n)
代码
Java实现
class Solution { public int countNicePairs(int[] nums) { // nums[i] + rev(nums[j]) == nums[j] + rev(nums[i]) // rev(nums[i]) - nums[i] == rev(nums[j]) = nums[j] int MOD = (int) Math.pow(10, 9) + 7; int res = 0; int n = nums.length; HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < n; i++) { int rev = helper(nums[i]); if (map.containsKey(nums[i] - rev)) { res += map.get(nums[i] - rev); res %= MOD; } map.put(nums[i] - rev, map.getOrDefault(nums[i] - rev, 0) + 1); } return res; } private int helper(int num) { int res = 0; while (num != 0) { res = res * 10 + num % 10; num /= 10; } return res; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
2021-01-17 [LeetCode] 1646. Get Maximum in Generated Array
2021-01-17 [LeetCode] 926. Flip String to Monotone Increasing