Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
couples-holding-hands.cpp 1.08 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2018-01-14 20:49 +08:00 . Update couples-holding-hands.cpp
// Time: O(n)
// Space: O(n)
class Solution {
public:
int minSwapsCouples(vector<int>& row) {
int N = row.size() / 2;
vector<vector<int>> couples(N);
for (int seat = 0; seat < row.size(); ++seat) {
couples[row[seat] / 2].emplace_back(seat / 2);
}
vector<vector<int>> adj(N);
for (const auto& couple : couples) {
adj[couple[0]].emplace_back(couple[1]);
adj[couple[1]].emplace_back(couple[0]);
}
int result = 0;
for (int couch = 0; couch < N; ++couch) {
if (adj[couch].empty()) {
continue;
}
int couch1 = couch;
int couch2 = adj[couch1].back(); adj[couch1].pop_back();
while (couch2 != couch) {
++result;
adj[couch2].erase(find(adj[couch2].begin(), adj[couch2].end(), couch1));
couch1 = couch2;
couch2 = adj[couch1].back(); adj[couch1].pop_back();
}
}
return result; // also equals to N - (# of cycles)
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助