Last active
September 1, 2022 08:05
-
-
Save yruslan/1211aca4d0581211769b904ffa4339ef to your computer and use it in GitHub Desktop.
A C++ solution to https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int soldiers(const vector<int>& row) { | |
// Need to use greater<int>() since the vector is descending, not assending | |
// It also explains lower_bound of 0 instead of 1 or 0.5 | |
auto it = lower_bound(row.begin(), row.end(), 0, greater<int>()); | |
return it-row.begin(); | |
} | |
vector<int> kWeakestRows(vector<vector<int>>& mat, int k) { | |
vector<pair<int, int> > weakness; | |
weakness.reserve(mat.size()); | |
for (int i=0; i<mat.size(); i++) | |
weakness.push_back(pair<int, int>(soldiers(mat[i]), i)); | |
std::partial_sort(weakness.begin(), weakness.begin() + k, weakness.end()); | |
vector<int> weakest; | |
weakest.reserve(k); | |
for (int i=0; i<k; i++) | |
weakest.push_back(weakness[i].second); | |
return weakest; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment