intmaxPathSum(TreeNode *root){ ans = INT_MIN; dfs(root); return ans; }
intdfs(TreeNode *root){ if (!root) return0; int left = 0, right = 0; if (root->left) left = max(0, dfs(root->left)); if (root->right) right = max(0, dfs(root->right)); ans = max(ans, root->val + left + right); return root->val + max(left, right); } };
classSolution { public: voidreorderList(ListNode *head){ if (!head || !head->next) return; int n = 0; for (auto q = head; q; q = q->next) n += 1; auto a = head; for (int i = 0; i < n / 2; ++i) a = a->next; auto b = a->next; a->next = nullptr; while (b) { auto c = b->next; b->next = a; a = b, b = c; } for (int i = 0; i < (n - 1) / 2; ++i) { auto c = a->next; a->next = head->next; auto d = head->next; head->next = a; head = d, a = c; } } };
LRUCache(int capacity) { cap = capacity; l = newNode(-1, -1), r = newNode(-1, -1); l->right = r; r->left = l; }
intget(int key){ if (hash.count(key)) { auto p = hash[key]; remove(p); insert(p); return p->val; } else { return-1; } }
voidput(int key, int value){ if (hash.count(key)) { auto p = hash[key]; p->val = value; remove(p); insert(p); } else { if (hash.size() == cap) { auto p = r->left; remove(p); hash.erase(p->key); delete p; } auto p = newNode(value, key); hash[key] = p; insert(p); } }
// 本题的解题思路在于如果两个链表相交,则遍历一遍所在链表到另一个链表的长度是相同的。 // 例如headA到相交点距离a,headB到相交点距离b,相交后的长度为c,因此a+c+b=b+c+a。因此本题可以用双指针解决 classSolution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB){ auto a = headA, b = headB; while (a != b) { a = a ? a->next : headB; b = b ? b->next : headA; } return a; } };
classSolution { public: vector<int> rightSideView(TreeNode *root){ vector<int> res; if (!root) return {}; queue < TreeNode * > q; q.push(root); while (q.size()) { int len = q.size(); for (int i = 0; i < len; ++i) { auto p = q.front(); q.pop(); if (p->left) q.push(p->left); if (p->right) q.push(p->right); if (i == len - 1) res.push_back(p->val); } } return res; } };
class Solution {
public:
const int dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, 1, -1};
int numIslands(vector <vector<char>> &grid) {
int res = 0;
for (int i = 0; i < grid.size(); ++i) {
for (int j = 0; j < grid[i].size(); ++j) {
if (grid[i][j] == '1') res += 1, dfs(grid, i, j);
}
}
return res;
}
void dfs(vector <vector<char>> &grid, int x, int y) {
grid[x][y] = '0';
for (int i = 0; i < 4; ++i) {
int di = x + dx[i], dj = y + dy[i];
if (di >= 0 && dj >= 0 && di < grid.size() && dj < grid[di].size() && grid[di][dj] == '1') dfs(grid, di, dj);
}
}
};