刷题第八天
1、最长重复子数组
给两个整数数组 A 和 B ,返回两个数组中公共的、长度最长的子数组的长度。
class Solution {
public:
int findLength(vector<int>& A, vector<int>& B) {
int n = A.size(), m = B.size();
vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
int res = 0;
for(int i = n - 1; i >= 0; i--){
for(int j = m - 1; j >= 0; j--){
dp[i][j] = A[i] == B[j] ? dp[i + 1][j + 1] + 1 : 0;
res = max(res, dp[i][j]);
}
}
return res;
}
};
``
2、删除链表的倒数第N个结点
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
```cpp
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(head == nullptr) return head;
ListNode* slow = head;
ListNode* fast = head;
while(n--){
fast = fast->next;
}
if(fast == nullptr) return head->next;
while(fast->next != nullptr){
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
return head;
}
};
3、二叉树的前序遍历
给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
class Solution {
public:
void preorder(TreeNode* root, vector<int> &res){
if(root == nullptr) return;
res.push_back(root->val);
preorder(root->left, res);
preorder(root->right, res);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
preorder(root, res);
return res;
}
};
4、二叉树的直径
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
class Solution {
public:
int res;
int diameterOfBinaryTree(TreeNode* root) {
depth(root);
return res - 1;
}
int depth(TreeNode* root){
if(root == nullptr) return 0;
int left = depth(root->left);
int right = depth(root->right);
res = max(left + right + 1, res);
return max(left, right) + 1;
}
};