|
| 1 | +# 1814. Count Nice Pairs in an Array |
| 2 | + |
| 3 | +- Difficulty: Medium. |
| 4 | +- Related Topics: Array, Hash Table, Math, Counting. |
| 5 | +- Similar Questions: Number of Pairs of Interchangeable Rectangles, Count Number of Bad Pairs, Number of Pairs Satisfying Inequality. |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +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: |
| 10 | + |
| 11 | + |
| 12 | + |
| 13 | +- `0 <= i < j < nums.length` |
| 14 | + |
| 15 | +- `nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])` |
| 16 | + |
| 17 | + |
| 18 | +Return **the number of nice pairs of indices**. Since that number can be too large, return it **modulo** `109 + 7`. |
| 19 | + |
| 20 | + |
| 21 | +Example 1: |
| 22 | + |
| 23 | +``` |
| 24 | +Input: nums = [42,11,1,97] |
| 25 | +Output: 2 |
| 26 | +Explanation: The two pairs are: |
| 27 | + - (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121. |
| 28 | + - (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12. |
| 29 | +``` |
| 30 | + |
| 31 | +Example 2: |
| 32 | + |
| 33 | +``` |
| 34 | +Input: nums = [13,10,35,24,76] |
| 35 | +Output: 4 |
| 36 | +``` |
| 37 | + |
| 38 | + |
| 39 | +**Constraints:** |
| 40 | + |
| 41 | + |
| 42 | + |
| 43 | +- `1 <= nums.length <= 105` |
| 44 | + |
| 45 | +- `0 <= nums[i] <= 109` |
| 46 | + |
| 47 | + |
| 48 | + |
| 49 | +## Solution |
| 50 | + |
| 51 | +```javascript |
| 52 | +/** |
| 53 | + * @param {number[]} nums |
| 54 | + * @return {number} |
| 55 | + */ |
| 56 | +var countNicePairs = function(nums) { |
| 57 | + var diffArray = nums.map(num => { |
| 58 | + var rev = Number(String(num).split('').reverse().join('')); |
| 59 | + return num - rev; |
| 60 | + }).sort((a, b) => a - b); |
| 61 | + var tmp = 0; |
| 62 | + var res = 0; |
| 63 | + var mod = Math.pow(10, 9) + 7; |
| 64 | + for (var i = 0; i < diffArray.length; i++) { |
| 65 | + tmp += 1; |
| 66 | + if (diffArray[i + 1] !== diffArray[i]) { |
| 67 | + res += tmp * (tmp - 1) / 2; |
| 68 | + res %= mod; |
| 69 | + tmp = 0; |
| 70 | + } |
| 71 | + } |
| 72 | + return res; |
| 73 | +}; |
| 74 | +``` |
| 75 | + |
| 76 | +**Explain:** |
| 77 | + |
| 78 | +nope. |
| 79 | + |
| 80 | +**Complexity:** |
| 81 | + |
| 82 | +* Time complexity : O(n * log(n)). |
| 83 | +* Space complexity : O(n). |
0 commit comments