Re: [闲聊] 每日leetcode

楼主: dont   2025-01-25 10:11:09
2948. Make Lexicographically Smallest Array by Swapping Elements
## 思路
先产生排序过的 {num, idx}
用UnionFind把可以互换的idx都加到同group
## Code
```cpp
class UnionFind {
public:
UnionFind(int size) {
rank_.resize(size, 1);
root_.resize(size, 0);
for (int i=0; i<size; ++i) {
root_[i] = i;
}
}
int findP(int x) {
if (root_[x] != x) {
root_[x] = findP(root_[x]);
}
return root_[x];
}
bool unionP(int x, int y) {
int rx = findP(x), ry = findP(y);
if (rx == ry) return false;
if (rank_[rx] >= rank_[ry]) {
root_[ry] = rx;
rank_[rx] += rank_[ry];
} else {
root_[rx] = ry;
rank_[ry] += rank_[rx];
}
return true;
}
private:
vector<int> root_;
vector<int> rank_;
};
class Solution {
public:
vector<int> lexicographicallySmallestArray(vector<int>& nums, int limit) {
int n = nums.size();
UnionFind uf(n);
vector<pair<int, int>> arr;
for (int i=0; i<n; ++i) {
arr.push_back({nums[i], i});
}
sort(arr.begin(), arr.end());
for (int i=1; i<n; ++i) {
if (arr[i].first - arr[i-1].first <= limit) {
uf.unionP(arr[i].second, arr[i-1].second);
}
}
unordered_map<int, queue<int>> groups;
for (auto& [num, idx]: arr) {
groups[uf.findP(idx)].push(num);
}
vector<int> res;
for (int i=0; i<n; ++i) {
int root = uf.findP(i);
res.push_back(groups[root].front());
groups[root].pop();
}
return res;
}
};
```

Links booklink

Contact Us: admin [ a t ] ucptt.com