Leetcode[2006] python3 implementation of number pairs whose absolute value of difference is K (counter count, one-time traversal)
編輯:Python
# Give you an array of integers nums And an integer k , Please return the number pair (i, j) Number of , Satisfy i < j And |nums[i] - nums[j]| == k .
#
#
# |x| The value of is defined as :
#
#
# If x >= 0 , Then the value is x .
# If x < 0 , Then the value is -x .
#
#
#
#
# Example 1:
#
# Input :nums = [1,2,2,1], k = 1
# Output :4
# explain : The absolute value of the difference is 1 The number pair of is :
# - [1,2,2,1]
# - [1,2,2,1]
# - [1,2,2,1]
# - [1,2,2,1]
#
#
# Example 2:
#
# Input :nums = [1,3], k = 3
# Output :0
# explain : The absolute value of any number pair difference is 3 .
#
#
# Example 3:
#
# Input :nums = [3,2,1,5,4], k = 2
# Output :3
# explain : The absolute value of the difference is 2 The number pair of is :
# - [3,2,1,5,4]
# - [3,2,1,5,4]
# - [3,2,1,5,4]
#
#
#
#
# Tips :
#
#
# 1 <= nums.length <= 200
# 1 <= nums[i] <= 100
# 1 <= k <= 99
#
# Related Topics Array Hashtable Count 44 0
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def countKDifference(self, nums: List[int], k: int) -> int:
ret = 0
cnt = Counter(nums)
for key in cnt.keys():
if key + k in cnt.keys():
ret += (cnt[key+k] * cnt[key])
if key - k in cnt.keys():
ret += (cnt[key-k] * cnt[key])
return ret // 2
# leetcode submit region end(Prohibit modification and deletion)