Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ed8979a

Browse files
2006. Count Number of Pairs With Absolute Difference K
1 parent bef415f commit ed8979a

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.cheehwatang.leetcode;
2+
3+
// Time Complexity : O(n^2),
4+
// where 'n' is the length of 'nums'.
5+
// We traverse 'nums' in a nested for-loop to count the pair with 'k' differences.
6+
//
7+
// Space Complexity : O(1),
8+
// as the auxiliary space used is independent of the input.
9+
10+
public class CountNumberOfPairsWithAbsoluteDifferenceK {
11+
12+
// Approach:
13+
// Intuitive and brute force approach to check every combination and count the ones with 'k' difference.
14+
15+
public int countKDifference(int[] nums, int k) {
16+
int count = 0;
17+
for (int i = 0; i < nums.length - 1; i++) {
18+
for (int j = i + 1; j < nums.length; j++) {
19+
if (Math.abs(nums[i] - nums[j]) == k) count++;
20+
}
21+
}
22+
return count;
23+
}
24+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /