题目描述
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.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode *root) {
if(!root) return 0;
int cnt=0;
cnt=max(maxDepth(root->left),cnt);
cnt=max(maxDepth(root->right),cnt);
return cnt+1;
}
};
题目描述
Say you have an array for which the i th element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
class Solution {
public:
int maxProfit(vector<int> &prices) {
int len=prices.size();
if(len<=1) return 0;
int res=0;
for(int i=1;i<len;i++)
{
if(prices[i]-prices[i-1]>0)
res+=prices[i]-prices[i-1];
}
return res;
}
};
题目描述
Given an array of integers, every element appears twiceexcept for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
class Solution {
public:
int singleNumber(int A[], int n) {
int res=0;
for(int i=0;i<n;i++)
res^=A[i];
return res;
}
};
题目描述
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).
class Solution {
public:
int reverse(int x) {
int num=abs(x);
int res=0;
while(num)
{
res=res*10+num%10;
num/=10;
}
if(x>0) return res;
else return res*(-1);
}
};