|
| 1 | +package com.cheehwatang.leetcode; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +// Time Complexity : O(n), |
| 7 | +// where 'n' is the length of 'nums'. |
| 8 | +// We traverse 'nums' to determine and count the relative values. |
| 9 | +// |
| 10 | +// Space Complexity : O(n), |
| 11 | +// where 'n' is the length of 'nums'. |
| 12 | +// We use a Hash Table to count the relative values, with a maximum size of 'n'. |
| 13 | + |
| 14 | +public class CountNicePairsInAnArray { |
| 15 | + |
| 16 | + // Approach: |
| 17 | + // First we need to understand the bad pair, i < j and nums[i] + rev(nums[j]) == nums[j] + rev(nums[i]). |
| 18 | + // With the brute force, we can check each and every pair if it is a nice pair, |
| 19 | + // but the algorithm will exceed the time limit. |
| 20 | + // Thus, let's change the equation for the bad pair as follows: |
| 21 | + // nums[i] - rev(nums[i]) == nums[j] - rev(nums[j]). |
| 22 | + // Use a HashMap to record the nums[i] - rev(nums[i]) for all the numbers, and the frequency. |
| 23 | + |
| 24 | + public int countNicePairs(int[] nums) { |
| 25 | + |
| 26 | + // Use long type, so as not the keep doing the modulo function, only need to do once at the end. |
| 27 | + long nicePairs = 0; |
| 28 | + Map<Integer, Integer> map = new HashMap<>(); |
| 29 | + |
| 30 | + for (int number : nums) { |
| 31 | + // Calculate the difference (relative value) between the nums[i] and rev(nums[i]). |
| 32 | + int relative = number - reverse(number); |
| 33 | + // If the map already had numbers with the same relative value, then add the frequency as the nice pairs. |
| 34 | + nicePairs += map.getOrDefault(relative, 0); |
| 35 | + // Increase the count in the map. |
| 36 | + map.put(relative, map.getOrDefault(relative, 0) + 1); |
| 37 | + } |
| 38 | + return (int) (nicePairs % (1e9 + 7)); |
| 39 | + } |
| 40 | + |
| 41 | + // Method to reverse the number. |
| 42 | + private int reverse(int number) { |
| 43 | + int reverse = 0; |
| 44 | + while (number > 0) { |
| 45 | + reverse = reverse * 10 + number % 10; |
| 46 | + number /= 10; |
| 47 | + } |
| 48 | + return reverse; |
| 49 | + } |
| 50 | +} |
0 commit comments