程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

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)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved