[LeetCode]#2006. Count Number of Pairs With Absolute Difference K
Nov 16, 2021
Environment: Python 3.8
Key technique: for, if
Given an integer array nums
and an integer k
, return the number of pairs (i, j)
where i < j
such that |nums[i] - nums[j]| == k
.
The value of |x|
is defined as:
x
ifx >= 0
.-x
ifx < 0
.
Example 1:
Input: nums = [1,2,2,1], k = 1
Output: 4
Explanation: The pairs with an absolute difference of 1 are:
- [1,2,2,1]
- [1,2,2,1]
- [1,2,2,1]
- [1,2,2,1]
Analysis:
- Brute Force method.
- Use two for loop and if to solve it.
Solution:
class Solution:
def countKDifference(self, nums, k):
ans=0
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if abs(nums[i]-nums[j]) ==k:
ans=ans+1
return ans
Submissions: