Fork me on GitHub

17th Jan 1814. 统计一个数组中好对子的数目(每日一题)

给你一个数组 nums ,数组中只包含非负整数。定义 rev(x) 的值为将整数 x 各个数字位反转得到的结果。比方说 rev(123) = 321rev(120) = 21 。我们称满足下面条件的下标对 (i, j)好的

  • 0 <= i < j < nums.length
  • nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])

请你返回好下标对的数目。由于结果可能会很大,请将结果对 10^9 + 7 取余 后返回。

输入:nums = [42,11,1,97]
输出:2
解释:两个坐标对为:
 - (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 。
  1. 运用了HashMap的特性
  2. 利用了加法交换律 将 nums[i] + rev(nums[j]) == nums[j] + rev(nums[i]) 交换为nums[i] - rev(nums[i]) == nums[j] - rev(nums[j]) 并且可以当做 f(x) = nuns[x] - rev(nums[x]) 进行处理 这样讲公式的两边下标统一 简化了算法
class Solution {
    public int countNicePairs(int[] nums) {
        final int MOD = (int)(Math.pow(10,9)) + 7;
      //累加结果得到最终的好下标对的数目
        int count = 0;
        HashMap<Integer, Integer> nicePairs = new HashMap<Integer,Integer>();
        int nums_len = nums.length;
      //翻转nums[i]
        for(int i = 0; i < nums_len; i++){
            int temp = nums[i];
            int j = 0;
            while(temp > 0){
                j = j * 10 + temp % 10;
                temp /= 10;
            }
            count = (count + nicePairs.getOrDefault(nums[i] - j, 0)) % MOD;
            nicePairs.put(nums[i] - j, nicePairs.getOrDefault(nums[i] - j, 0) + 1);
        }
        return count;
    }
}
posted @ 2023-01-17 19:40  RickieRun  阅读(25)  评论(0)    收藏  举报
Live2D