파비의 매일매일 공부기록

2023.11.22 Today's Challenge 본문

Problem Solving/LeetCode

2023.11.22 Today's Challenge

fabichoi 2023. 11. 22. 23:45

https://leetcode.com/problems/count-nice-pairs-in-an-array/

 

Count Nice Pairs in an Array - LeetCode

Can you solve this real interview question? 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

leetcode.com

해쉬맵으로 푸는 문제

class Solution:
    def countNicePairs(self, nums: List[int]) -> int:
        def rev(num):
            res = 0
            while num:
                res = res * 10 + num % 10
                num //= 10
            return res

        arr = []
        for i in range(len(nums)):
            arr.append(nums[i] - rev(nums[i]))

        d = defaultdict(int)
        ans = 0
        MOD = 10 ** 9 + 7

        for num in arr:
            ans = (ans + d[num]) % MOD
            d[num] += 1
        
        return ans
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.11.24 Today's Challenge  (1) 2023.11.24
2023.11.23 Today's Challenge  (1) 2023.11.23
2023.11.21 Today's Challenge  (0) 2023.11.21
2023.11.20 Today's Challenge  (1) 2023.11.20
2023.11.19 Today's Challenge  (0) 2023.11.19
Comments