365天挑战LeetCode1000题——Day 100 零矩阵 从链表中删去总和值为零的连续节点 地图中的最高点
面试题 01.08. 零矩阵
代码实现
class Solution {
public:void setZeroes(vector<vector<int>>& matrix) {set<int> r, c;int m = matrix.size();int n = matrix[0].size();for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {if (!matrix[i][j]) {r.emplace(i);c.emplace(j);}}}for (auto it = r.begin(); it != r.end(); it++) {for (int j = 0; j < n; j++) {matrix[*it][j] = 0;}}for (auto it = c.begin(); it != c.end(); it++) {for (int i = 0; i < m; i++) {matrix[i][*it] = 0;}}}
};
1171. 从链表中删去总和值为零的连续节点
代码实现
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:ListNode* removeZeroSumSublists(ListNode* head) {ListNode* traverse = head;vector<int> arr;while (traverse) {arr.push_back(traverse->val);traverse = traverse->next;}bool flag = true;while (flag) {flag = false;auto it = arr.begin();for (int i = 0; i < arr.size(); i++) {int sum = 0;auto tmp = it;for (int j = i; j < arr.size(); j++) {sum += *tmp;// cout << *tmp << endl;tmp++;if (sum == 0) {// cout << "fiajw" << endl;for (int k = 0; k < j - i + 1; k++) {it = arr.erase(it);}flag = true;break;}}it++;if (flag) break;}}if (arr.empty()) return nullptr;while (head->val != arr[0]) head = head->next;ListNode* pre = head, *nex = head->next;for (int i = 1; i < arr.size(); i++) {while (nex->val != arr[i]) nex = nex->next;pre->next = nex;pre = nex;nex = nex->next;}pre->next = nullptr;return head;}
};
面试题 1765. 地图中的最高点
代码实现(BFS)
class Solution {
public:vector<vector<int>> highestPeak(vector<vector<int>>& isWater) {int m = isWater.size();int n = isWater[0].size();queue<pair<int, int>> myQueue;vector<vector<bool>> visited(m, vector<bool>(n));vector<vector<int>> ans = isWater;for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {if (isWater[i][j]) {ans[i][j] = 0;visited[i][j] = true;if (i - 1 >= 0 && !isWater[i - 1][j]) myQueue.push({i - 1, j});// if (i == 4) cout << myQueue.size() << endl;if (i + 1 < m && !isWater[i + 1][j]) myQueue.push({i + 1, j});if (i == 4) cout << myQueue.size() << endl;if (j - 1 >= 0 && !isWater[i][j - 1]) myQueue.push({i, j - 1});if (j + 1 < n && !isWater[i][j + 1]) myQueue.push({i, j + 1}); }}}int height = 1;while (myQueue.size()) {int sz = myQueue.size();// cout << height << " : ";while (sz--) {auto[i, j] = myQueue.front();// cout << "(" <myQueue.pop();if (visited[i][j]) continue;visited[i][j] = true;ans[i][j] = height;if (i - 1 >= 0 && !visited[i - 1][j]) {myQueue.push({i - 1, j});}if (i + 1 < m && !visited[i + 1][j]) {myQueue.push({i + 1, j});}if (j - 1 >= 0 && !visited[i][j - 1]) {myQueue.push({i, j - 1});}if (j + 1 < n && !visited[i][j + 1]) {myQueue.push({i, j + 1});} }// cout << endl;height++;}return ans;}
};
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!