Skip to content

Instantly share code, notes, and snippets.

@yruslan
Last active September 1, 2022 08:05
Show Gist options
  • Save yruslan/1211aca4d0581211769b904ffa4339ef to your computer and use it in GitHub Desktop.
Save yruslan/1211aca4d0581211769b904ffa4339ef to your computer and use it in GitHub Desktop.
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