-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathcardiSort.cpp
More file actions
110 lines (89 loc) · 2.4 KB
/
cardiSort.cpp
File metadata and controls
110 lines (89 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <iostream>
#include <map>
#include <set>
#include <algorithm>
#include <iterator>
#include <vector>
using namespace std;
// g++ cardiSort.cpp -std=c++17
class Solution
{
public:
vector<int> cardiSort(vector<int> nums)
{
map<int, int> m;
for(int i=0; i<nums.size(); i++)
{
m[nums[i]] = countOnes(nums[i]);
}
multiset<pair<int, int>, ValueComparator> sorted_set(m.begin(), m.end());
vector<int> result;
result.reserve(sorted_set.size());
for(const auto& pair : sorted_set)
{
result.push_back(pair.first);
}
return result;
}
private:
int countOnes(int n) {
int count = 0;
while (n) {
count += n & 1;
n >>= 1;
}
return count;
}
// Comparator for sorting by value
struct ValueComparator {
bool operator()(const pair<int, int>& lhs,
const pair<int, int>& rhs) const {
return lhs.second < rhs.second;
}
};
};
class SolutionWithMultiMap
{
public:
vector<int> cardiSort(vector<int> nums)
{
map<int, int> m;
for(int i=0; i<nums.size(); i++)
{
m[nums[i]] = countOnes(nums[i]);
}
multimap<int, ValueComparator> sorted_set;
for (const auto& kv : m) {
sorted_set.insert(std::make_pair(kv.second, ValueComparator(kv.first)));
}
vector<int> result;
for(const auto& pair : sorted_set)
{
result.push_back(pair.second.value);
}
return result;
}
private:
int countOnes(int n) {
int count = 0;
while (n) {
count += n & 1;
n >>= 1;
}
return count;
}
// Comparator for sorting by value
class ValueComparator {
public:
int value;
ValueComparator(int v) : value(v) {}
};
};
int main() {
vector<int> nums {5, 1, 2, 3, 4, 5};
for(auto c : Solution{}.cardiSort(nums))
{
std::cout<<c<<" ";
}
return 0;
}