Leetcode刷题

1.二叉树的直径
描述:给定一棵二叉树,计算其直径。一棵二叉树的直径是任意两个结点路径长度的最大值,这条直径可能穿过也可能不穿过根节点。
示例:
1
/
2 3
/ \
4 5
返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
课题思路:
如果经过根结点,则直径(最长路径长度)即为左子树高度+右子树高度;
若不经过根结点,则需要计算每个结点左子树和右子树的高度,并求出最大值。

C++代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 
class Solution {
	int result = 0;
    
public:
    int diameterOfBinaryTree(TreeNode* root) {
       depth(root);
       //深度
       return result;
    }

	int depth(TreeNode *root){
		if(root == NULL)
			return 0;//递归出口
		//分别递归来求得左右子树的深度
		int leftdepth = depth(root->left);
		int rightdepth = depth(root->right);
		result = max(result,leftdepth+rightdepth);
		//返回以此节点为根的树的深度
		return max(leftdepth,rightdepth) + 1;
	}
};

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。

注意你不能在买入股票前卖出股票。
思路:
买入和卖出构成一个数对,利润就是这个数对的差,最大利润就是所有数对差的最大值。(注意:卖出要在买入之后)

思路一:

本题最容易想到的方法应该是暴力法:找出数组中所有的数对并求出差,取其中的最大值即可,简单粗暴。时间复杂度:O(n2)O(n2)。

思路二:

在遍历数组时,我们可以顺便记录下其中的最小值(即股票最低价),作为买入的时间。同时,计算如果现在卖出,利润是多少,遍历完数组,即可求得最大利润。时间复杂度:O(n)O(n)。

代码实现:

public class Solution {
    public int maxProfit(int prices[]) {
        int maxprofit = 0;
        for (int i = 0; i < prices.length - 1; i++) {
            for (int j = i + 1; j < prices.length; j++) {
                int profit = prices[j] - prices[i];
                if (profit > maxprofit)
                    maxprofit = profit;
            }
        }
        return maxprofit;
    }
}
或者:
class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length < 2) {
            return 0;
        }
        // 初始化最大利润为0,股票最低价为第一天
        int maxProfit = 0, min = prices[0];

        for (int i = 1; i < prices.length; i++) {
            // 更新股票最低价
            if (prices[i] < min) {
                min = prices[i];
            }
            // 更新最大利润
            if (prices[i] - min > maxProfit) {
                maxProfit = prices[i] - min;
            }
        }
        return maxProfit;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值