11package com .fishercoder .solutions ;
22
3- import java .util .Arrays ;
43import java .util .HashMap ;
5- import java .util .HashSet ;
6- import java .util .List ;
74import java .util .Map ;
8- import java .util .Set ;
95
106/**
7+ * 532. K-diff Pairs in an Array
8+ *
119 * Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array.
1210 * Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.
1311
@@ -34,36 +32,29 @@ The pairs (i, j) and (j, i) count as the same pair.
3432 */
3533public class _532 {
3634
37- //this O(n^2) will result in TLE
38- public int findPairs_On2 (int [] nums , int k ) {
39- Set <List <Integer >> pairsSet = new HashSet <>();
40- for (int i = 0 ; i < nums .length - 1 ; i ++) {
41- for (int j = i + 1 ; j < nums .length ; j ++) {
42- if (Math .abs (nums [j ] - nums [i ]) == k ) {
43- pairsSet .add (nums [i ] > nums [j ] ? Arrays .asList (nums [j ], nums [i ]) : Arrays .asList (nums [i ], nums [j ]));
44- }
45- }
46- }
47- return pairsSet .size ();
48- }
49-
5035 public int findPairs (int [] nums , int k ) {
51- if (nums == null || nums .length == 0 || k < 0 ) return 0 ;
36+ if (nums == null || nums .length == 0 || k < 0 ) {
37+ return 0 ;
38+ }
5239
5340 Map <Integer , Integer > map = new HashMap ();
54- for (int i : nums ) {
55- map .put (i , map .getOrDefault (i , 0 ) + 1 );
41+ for (int num : nums ) {
42+ map .put (num , map .getOrDefault (num , 0 ) + 1 );
5643 }
5744
5845 int answer = 0 ;
5946 for (int key : map .keySet ()) {
6047 if (k == 0 ) {
61- if (map .get (key ) >= 2 ) answer ++;
48+ if (map .get (key ) >= 2 ) {
49+ answer ++;
50+ }
6251 } else {
63- if (map .containsKey (key + k )) answer ++;
52+ if (map .containsKey (key + k )) {
53+ answer ++;
54+ }
6455 }
6556 }
6657 return answer ;
6758 }
6859
69- }
60+ }
0 commit comments