LeetCode104原题:
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
题意就是求一棵数的深度,很简单利用递归就可以很快求出来
class Solution {
public:
int maxDepth(TreeNode* root) {
int i = 0;
return depth(root,i);
}
private:
int depth(TreeNode* root,int d){
if(root == NULL)return d;
else d++;
return max(depth(root->left,d),depth(root->right,d));
}
};
LeetCode121原题
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example1:Input: [7, 1, 5, 3, 6, 4],Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example2:Input: [7, 6, 4, 3, 1],Output: 0
In this case, no transaction is done, i.e. max profit = 0.
题意就是找一天收股票,找一个天卖出去,求最大的收益,很多方法做这题,但是尽量使其运行时间短,最短的时间复杂度应该是O(n),所以尽可能循环到哪个位置就求到它的最大利益。所以我们可以对每个元素,先求到它之前的最小值,再根据它当前的值减去最小值,若收益更大,则替换最大收益值。
算法如下:
class Solution {
public:
int maxProfit(vector<int> &prices) {
int maxPro = 0;
int minPrice = INT_MAX;
for(int i = 0; i < prices.size(); i++){
minPrice = min(minPrice, prices[i]);
maxPro = max(maxPro, prices[i] - minPrice);
}
return maxPro;
}
};
LeetCode121原题
Count the number of prime numbers less than a non-negative number, n.
虽然是很简单的一道题,这题我提交了不少的次数才通过(因为超时),主要还是因为考虑得不够好。题目大意就是让我们统计 n 之前的所有素数。一个好办法就是建立一个vector,vector【i】就是表示这个 i 是不是素数,从2开始直到N,对每个 i ,若它是素数,则的倍数我们知道它必然不是素数,那么我们可以直接将vector【i】设置成非素数。这样比一个个判断要快速许多。
具体代码如下:
class Solution {
public:
int countPrimes(int n) {
vector<bool> isprime(n,true);
if(n <= 1)return 0;
isprime[0] = false;
isprime[1] = false;
for(int i = 2;i < n;i ++){
if(isprime[i]){
for(int j = 2 * i; j < n;j = j + i){
isprime[j] = false;
}
}
}
return count(isprime.begin(),isprime.end(),true);
}
};