当前位置:网站首页>LeetCode 2006. Number of pairs whose absolute value of difference is k

LeetCode 2006. Number of pairs whose absolute value of difference is k

2022-06-24 03:39:00 freesan44

Title address (2006. The absolute value of the difference is K Number to number )

https://leetcode-cn.com/problems/count-number-of-pairs-with-absolute-difference-k/

Title Description

 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

Ideas

Violence solution

Code

  • Language support :Python3

Python3 Code:

class Solution:
    def countKDifference(self, nums: List[int], k: int) -> int:
        length = len(nums)
        res = 0
        for i in range(length):
            for j in range(i+1,length):
                if k == abs(nums[i]-nums[j]):
                    res += 1
        return res

Complexity analysis

Make n Is array length .

  • Time complexity :$O(nlogn)$
  • Spatial complexity :$O(1)$
原网站

版权声明
本文为[freesan44]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/09/20210922194430830o.html