From 874a36ed5c1643be3fa92ba03168fdc851e8b632 Mon Sep 17 00:00:00 2001 From: Lam Haoyin Date: Sun, 27 Mar 2022 10:18:38 +0800 Subject: [PATCH] add: 220327 [cpp] --- cpp/2203/220327.cpp | 44 +++++++++++++++++++++++++++++++++++++++++ cpp/2203/CMakeLists.txt | 2 +- 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 cpp/2203/220327.cpp diff --git a/cpp/2203/220327.cpp b/cpp/2203/220327.cpp new file mode 100644 index 0000000..d1a5958 --- /dev/null +++ b/cpp/2203/220327.cpp @@ -0,0 +1,44 @@ +#include +#include +#include + +/** + * 1337. The K Weakest Rows in a Matrix + * You are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1's will appear to the left of all the 0's in each row. + * A row i is weaker than a row j if one of the following is true: + * - The number of soldiers in row i is less than the number of soldiers in row j. + * - Both rows have the same number of soldiers and i < j. + * Return the indices of the k weakest rows in the matrix ordered from weakest to strongest. + * + * 100%, pure, STL solution! + */ + +class Solution { +public: + static std::vector kWeakestRows(const std::vector>& mat, int k) { + int n = mat.size(); + std::vector*>> idMat(n); + for (int i = 0; i < n; ++i) + idMat[i] = {i, &mat[i]}; + std::sort(idMat.begin(), idMat.end(), [](const std::pair*>& x, const std::pair*>& y) { + auto xPos = std::distance(x.second->begin(), std::lower_bound(x.second->begin(), x.second->end(), 0, std::greater<>())); + auto yPos = std::distance(y.second->begin(), std::lower_bound(y.second->begin(), y.second->end(), 0, std::greater<>())); + return (xPos == yPos) ? (x < y) : (xPos < yPos); + }); + std::vector ret(k); + for (int i = 0; i < k; ++i) + ret[i] = idMat[i].first; + return ret; + } +}; + +int main() { + auto ret = Solution::kWeakestRows({{1,1,0,0,0}, + {1,1,1,1,0}, + {1,0,0,0,0}, + {1,1,0,0,0}, + {1,1,1,1,1}}, 3); + for (int i : ret) + std::cout << i << ' '; + return 0; +} diff --git a/cpp/2203/CMakeLists.txt b/cpp/2203/CMakeLists.txt index 5466d63..727a57f 100644 --- a/cpp/2203/CMakeLists.txt +++ b/cpp/2203/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2203) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2203 220326-CN.cpp) +ADD_EXECUTABLE(2203 220327.cpp)