Skip to content

Instantly share code, notes, and snippets.

@willzhang05
Last active March 15, 2020 04:44
Show Gist options
  • Save willzhang05/1de70b5aaa2b35a617dc3d64acc6ab9c to your computer and use it in GitHub Desktop.
Save willzhang05/1de70b5aaa2b35a617dc3d64acc6ab9c to your computer and use it in GitHub Desktop.
std::vector<int> customSortNumbers(std::vector<int> arr) {
// arr[0] = 1
// count[1] = 1
// count[arr[i]]
// map
/*
{1, 1}
{2, 3}
{4, 2}
*/
std::map<int, int> occurrences;
// {{1, 1},{4, 2},{2, 3}}
std::pair<int,int> temp_occurrence;
for (int i = 0; i < arr.size(); ++i) {
//printf("occurrences: %d %d\n", arr[i], occurrences[arr[i]]);
if (occurrences.find(arr[i]) != occurrences.end()) {
occurrences[arr[i]] += 1;
} else {
temp_occurrence = {arr[i], 1};
occurrences.insert(temp_occurrence);
}
}
std::set<std::pair<int,int>> output_set;
auto it = occurrences.begin();
std::pair<int, int> temp;
while (it != occurrences.end()) {
temp = *it;
output_set.insert({temp.second, temp.first});
//printf("%d %d\n", temp.first, temp.second);
++it;
}
auto set_it = output_set.begin();
std::vector<int> output;
while (set_it != output_set.end()) {
temp = *set_it;
for (int k = 0; k < temp.first; ++k) {
output.push_back(temp.second);
}
++set_it;
}
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment