|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# 1814. Count Nice Pairs in an Array |
| 4 | +# Medium |
| 5 | +# https://leetcode.com/problems/count-nice-pairs-in-an-array |
| 6 | + |
| 7 | +=begin |
| 8 | +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: |
| 9 | +* 0 <= i < j < nums.length |
| 10 | +* nums[i] + rev(nums[j]) == nums[j] + rev(nums[i]) |
| 11 | +Return the number of nice pairs of indices. Since that number can be too large, return it modulo 109 + 7. |
| 12 | +
|
| 13 | +Example 1: |
| 14 | +Input: nums = [42,11,1,97] |
| 15 | +Output: 2 |
| 16 | +Explanation: The two pairs are: |
| 17 | +- (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121. |
| 18 | +- (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12. |
| 19 | +
|
| 20 | +Example 2: |
| 21 | +Input: nums = [13,10,35,24,76] |
| 22 | +Output: 4 |
| 23 | +
|
| 24 | +Constraints: |
| 25 | +1 <= nums.length <= 105 |
| 26 | +0 <= nums[i] <= 109 |
| 27 | +=end |
| 28 | + |
| 29 | +# @param {Integer[]} nums |
| 30 | +# @return {Integer} |
| 31 | +def count_nice_pairs(nums) |
| 32 | + y = Hash.new { |h, x| h[x] = x - x.to_s.reverse.to_i } |
| 33 | + res = 0 |
| 34 | + c = Hash.new(0) |
| 35 | + for x in nums |
| 36 | + res += c[y[x]] |
| 37 | + c[y[x]] += 1 |
| 38 | + end |
| 39 | + res % 1000000007 |
| 40 | +end |
| 41 | + |
| 42 | +# **************** # |
| 43 | +# TEST # |
| 44 | +# **************** # |
| 45 | + |
| 46 | +require "test/unit" |
| 47 | +class Test_count_nice_pairs < Test::Unit::TestCase |
| 48 | + def test_ |
| 49 | + assert_equal 2, count_nice_pairs([42, 11, 1, 97]) |
| 50 | + assert_equal 4, count_nice_pairs([13, 10, 35, 24, 76]) |
| 51 | + end |
| 52 | +end |
0 commit comments