diff --git a/cpp/evaluate-reverse-polish-notation.cpp b/cpp/evaluate-reverse-polish-notation.cpp index 8e5e2a8..58cddbe 100644 --- a/cpp/evaluate-reverse-polish-notation.cpp +++ b/cpp/evaluate-reverse-polish-notation.cpp @@ -4,8 +4,8 @@ #include <vector> class Solution { - static auto - get_function(const std::string &op) -> std::function<int(int, int)> { + static auto get_function(const std::string &op) + -> std::function<int(int, int)> { if (op == "+") { return std::plus<int>{}; } else if (op == "-") { diff --git a/cpp/make-lexicographically-smallest-array-by-swapping-elements.cpp b/cpp/make-lexicographically-smallest-array-by-swapping-elements.cpp new file mode 100644 index 0000000..2886f64 --- /dev/null +++ b/cpp/make-lexicographically-smallest-array-by-swapping-elements.cpp @@ -0,0 +1,37 @@ +#include <algorithm> +#include <list> +#include <unordered_map> +#include <vector> + +class Solution { + public: + auto lexicographicallySmallestArray(std::vector<int> nums, int limit) + -> std::vector<int> { + // sort the numbers + auto sorted_nums = nums; + std::sort(sorted_nums.begin(), sorted_nums.end()); + + // assign groups + std::unordered_map<int, int> num_to_group; + std::unordered_map<int, std::list<int>> groups; + + auto group = 0; + for (auto i = 0u; i < sorted_nums.size(); ++i) { + if (i > 0 && sorted_nums[i] - sorted_nums[i - 1] > limit) { + ++group; + } + + num_to_group[sorted_nums[i]] = group; + groups[group].push_back(sorted_nums[i]); + } + + // emplace into original ‹nums› + for (auto &x : nums) { + group = num_to_group[x]; + x = *groups[group].begin(); + groups[group].pop_front(); + } + + return nums; + } +};