编辑
2023-10-31
数据结构与算法
00
请注意,本文编写于 557 天前,最后修改于 557 天前,其中某些信息可能已经过时。

image.png

题目

刚开始想到的做法比较朴素,但是能过,相当于暴力,用一个哈希表,key存储每一行的索引,value存储每一行的总和,定义排序规则,value相等按key排序,不然直接按value大小排序,直接输出前k位的key就好。

cpp
class Solution { public: static bool compare(const std::pair<int, int>& a, const std::pair<int, int>& b) { if (a.second == b.second) { return a.first < b.first; } return a.second < b.second; } std::vector<int> kWeakestRows(std::vector<std::vector<int>>& mat, int k) { std::unordered_map<int, int> counts; // 遍历矩阵的每一行,计算军人总数并存储到 counts 哈希表中 for (int i = 0; i < mat.size(); i++) { int count = 0; for (int j = 0; j < mat[i].size(); j++) { count += mat[i][j]; } counts[i] = count; } // 对 counts 哈希表进行排序,排序规则是先按总数排序,若总数相等则按索引排序 std::vector<std::pair<int, int>> sorted_counts(counts.begin(), counts.end()); std::sort(sorted_counts.begin(), sorted_counts.end(), compare); // 取出前 k 个索引,存储到结果向量中 std::vector<int> result; for (int i = 0; i < k; i++) { result.push_back(sorted_counts[i].first); } return result; } };

这样消耗的空间比较大,但是朴素又简单。后面想一下,这哈希表好像没有屁用。。。

cpp
class Solution { public: static bool compare(const std::pair<int, int>& a, const std::pair<int, int>& b) { if (a.second == b.second) { return a.first < b.first; } return a.second < b.second; } std::vector<int> kWeakestRows(std::vector<std::vector<int>>& mat, int k) { std::vector<std::pair<int, int>> counts; // 遍历矩阵的每一行,计算军人总数并存储到 counts 中 for (int i = 0; i < mat.size(); i++) { int count = 0; for (int j = 0; j < mat[i].size(); j++) { count += mat[i][j]; } counts.push_back({i, count}); } // 对 counts 进行排序,排序规则是先按总数排序,若总数相等则按索引排序 std::sort(counts.begin(), counts.end(), compare); // 取出前 k 个索引,存储到结果向量中 std::vector<int> result; for (int i = 0; i < k; i++) { result.push_back(counts[i].first); } return result; } };

本文作者:yowayimono

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!