cpp: add «2948. Make Lexicographically Smallest Array by Swapping Elements»
URL: https://leetcode.com/problems/make-lexicographically-smallest-array-by-swapping-elements/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
a67853e75f
commit
dd48e58a2c
2 changed files with 39 additions and 2 deletions
|
@ -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 == "-") {
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
};
|
Loading…
Add table
Reference in a new issue