Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
minimum-domino-rotations-for-equal-row.cpp 1.51 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2019-03-11 01:14 +08:00 . Update minimum-domino-rotations-for-equal-row.cpp
// Time: O(n)
// Space: O(1)
class Solution {
public:
int minDominoRotations(vector<int>& A, vector<int>& B) {
set<int> intersect{A[0], B[0]};
for (int i = 1; i < A.size() && !intersect.empty(); ++i) {
const auto s1 = move(intersect);
const set<int> s2{A[i], B[i]};
set_intersection(s1.cbegin(), s1.cend(),
s2.cbegin(), s2.cend(),
inserter(intersect, intersect.begin()));
}
if (intersect.empty()) {
return -1;
}
const auto& x = *intersect.cbegin();
return min(A.size() - count(A.cbegin(), A.cend(), x),
B.size() - count(B.cbegin(), B.cend(), x));
}
};
// Time: O(n)
// Space: O(1)
class Solution2 {
public:
int minDominoRotations(vector<int>& A, vector<int>& B) {
unordered_set<int> intersect{A[0], B[0]};
for (int i = 1; i < A.size() && !intersect.empty(); ++i) {
const auto s1 = move(intersect);
const unordered_set<int> s2{A[i], B[i]};
copy_if(s1.cbegin(), s1.cend(),
inserter(intersect, intersect.begin()),
[&s2](const int x) {
return s2.count(x) > 0;
});
}
if (intersect.empty()) {
return -1;
}
const auto& x = *intersect.cbegin();
return min(A.size() - count(A.cbegin(), A.cend(), x),
B.size() - count(B.cbegin(), B.cend(), x));
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助