Number of Excellent Pairs LeetCode solution in Java

1
class Solution {
2
public long countExcellentPairs(int[] nums, int k) {
3
HashMap<Integer, Set<Integer>> map = new HashMap<>();
4
for (int i : nums) {
5
int x = Integer.bitCount(i);
6
map.putIfAbsent(x, new HashSet<>());
7
map.get(x).add(i);
8
}
9
long ans = 0;
10
HashSet<Integer> vis = new HashSet<>();
11
for (int i : nums) {
12
if (vis.contains(i)) continue;
13
int need = Math.max(0, k - Integer.bitCount(i));
14
for (int key : map.keySet()) // runs at max 30 times
15
if (key >= need) ans += (long) map.get(key).size();
16
vis.add(i);
17
}
18
return ans;
19
}
20
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0