[LeetCode]#2006. Count Number of Pairs With Absolute Difference K

Fatboy Slim
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 if x >= 0.
  • -x if x < 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:

  1. Brute Force method.
  2. 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:

--

--

Fatboy Slim
Fatboy Slim

Written by Fatboy Slim

Interesting in any computer science.

No responses yet