2021-06-14

刷题第八天
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;
	}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值