|
| 1 | +// Time: O(n) |
| 2 | +// Space: O(1) |
| 3 | + |
| 4 | +class Solution { |
| 5 | +public: |
| 6 | + int minDominoRotations(vector<int>& A, vector<int>& B) { |
| 7 | + set<int> intersect{A[0], B[0]}; |
| 8 | + for (int i = 1; i < A.size(); ++i) { |
| 9 | + const set<int> s1{A[i], B[i]}; |
| 10 | + const auto s2 = move(intersect); |
| 11 | + set_intersection(s1.cbegin(), s1.cend(), |
| 12 | + s2.cbegin(), s2.cend(), |
| 13 | + inserter(intersect, intersect.begin())); |
| 14 | + } |
| 15 | + if (intersect.empty()) { |
| 16 | + return -1; |
| 17 | + } |
| 18 | + auto x = *intersect.begin(); |
| 19 | + return min(A.size() - count(A.begin(), A.end(), x), |
| 20 | + B.size() - count(B.begin(), B.end(), x)); |
| 21 | + } |
| 22 | +}; |
| 23 | + |
| 24 | +// Time: O(n) |
| 25 | +// Space: O(1) |
| 26 | +class Solution2 { |
| 27 | +public: |
| 28 | + int minDominoRotations(vector<int>& A, vector<int>& B) { |
| 29 | + unordered_set<int> intersect{A[0], B[0]}; |
| 30 | + for (int i = 1; i < A.size(); ++i) { |
| 31 | + const unordered_set<int> s1{A[i], B[i]}; |
| 32 | + const auto s2 = move(intersect); |
| 33 | + copy_if(s1.cbegin(), s1.cend(), |
| 34 | + inserter(intersect, intersect.begin()), |
| 35 | + [&s2](const int x) { |
| 36 | + return s2.count(x) > 0; |
| 37 | + }); |
| 38 | + } |
| 39 | + if (intersect.empty()) { |
| 40 | + return -1; |
| 41 | + } |
| 42 | + auto x = *intersect.begin(); |
| 43 | + return min(A.size() - count(A.begin(), A.end(), x), |
| 44 | + B.size() - count(B.begin(), B.end(), x)); |
| 45 | + } |
| 46 | +}; |
0 commit comments