Number of Excellent Pairs LeetCode solution in C++
1class Solution {2public:3typedef long long ll;4int setbits(int n) {5int cnt = 0;6while (n) {7cnt += (n % 2);8n /= 2;9}10return cnt;11}1213long long countExcellentPairs(vector<int> &nums, int k) {14unordered_set<int> s(nums.begin(), nums.end());15vector<int> v;16for (auto &i : s) {17int x = setbits(i);18v.push_back(x);19}20sort(v.begin(), v.end());2122ll ans = 0;23for (int i = 0; i < v.size(); i++) {24auto it = lower_bound(v.begin(), v.end(), k - v[i]);25ans += (v.end() - it);26}27return ans;28}29};